1
Server-side:
PHP and MySQL (continued)
• some remarks …
• check on variable:
isset
( $variable ) ?
• more functionality in a single form
• more functionality in a single PHP-file …
• updating the database
• data validation at server-side (always!)
• regular expressions with PHP
2
mysql_real_escape_string
mysql_real_escape_string -function were reported…
The mysql_real_escape_string(..)function requires a connection to the database to be open.
If one isn't open it will try to open one with the existing defaults.
All you need to do is make sure you connect to the mysql database before using mysql_real_escape_string(..). 3 ! ! ! " ! ! # $ # % % ! & ' () * + , ! -&- ! ! ! . ! # % / 00 / 00 / 00 4
Suggestion: the ‘
here document’
- variant of php-echo:
echo <<<XXX
……..
XXX;
For instance: echo <<<END
This uses the "here document" syntax to output multiple lines with $variable interpolation. Note that the here document terminator must appear on a line with just a semicolon. No extra whitespace!
END;
echo <<<MYEND
<form action="" method="POST" name="userinput" > <b><i>Your query-command:</i></b>
<input type="text" name="querytext" value="$querytext"size="40" /> <input type="submit" value="Submit query" />
</form> MYEND; 5
1
!
2
1 ! 3 4 ! 5 ! 36 4 37 4 , ! 3 ! 4 8 3 ! 4 2 6 <html><head><title>More submits</title></head> <body><h4>Example with more 'submits'</h4><formid="myform" action="http://www.../echoformdata.php" method="post" > <table>
<tr><td>Membernr.:</td><td><input type="text" name="number" size=4 /></td></tr> <tr><td>Firstname:</td><td><input type="text" name="firstname" size=8 /></td></tr> <tr><td><input type="submit" name="idsubmit" value="Change"/></td> <td><input type="submit" name="idsubmit" value="Delete"/></td></tr> </table>
</form></body></html>
9 6
9 7
!
2
Response from server-side:
Next form data arrived by 'POST'-method: number = 12 firstname = Alice
idsubmit = Change
Next form data arrived by 'POST'-method: number = 12 firstname = Alice idsubmit = Delete or: !
if ( isset ( $_POST [ 'idsubmit' ]) )
{ . . . .
if ( $idsubmit == "Delete" )
7
1
! -&-
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" … > <html><head><title>Combining functionality in one file</ title> <link href="mystyles.css" rel="StyleSheet" type="text/css" /> <script src="javascripts.js" type="text/javascript"></script></head>
<body> <div class="top"> <?php include "top.inc" ; ?> </div> <div class="main"> <?php
if ( ! isset ( $_POST [ 'fullname' ) ) include 'startform.html' ; else { include 'startform.html' ; include 'request.php' ; } ?> </div> </body></html> 6 # 4 % !
<= willalwaysbe shown
<= only shownat startup <= shownat ‘second’ call
(with a posted ‘fullname’) Later: we ‘ll look to the alternative: ‘startform.php’ !
Alternatives (more or less..):
if ( empty( $_POST ['fullname'] )) if ( ! $_POST ['fullname'] ) // n.p. 8
1
!
-&-
2 #
%
Content of ‘startform.html’: <h4>The 'startform.html'-part</h4><form name="testform" method="post" action="" > <table>
<tr><td>Name:</td>
<td><input type="text" name="fullname"value="" /></td></tr> <tr><td>Age:</td>
<td><input type="text" name="age"value="" /></td></tr> <tr><td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Reset" />
<input type="button" value="Clear" onclick="clear_all();"/> </td></tr>
</table></form>
<?php
$fullname = $_POST['fullname'] ;
$age = $_POST['age'] ;
echo "<p />Received: values: '$fullname' and '$age' to .." ; ?>
Content of ‘request.php’: Fields are empty! Why?
action="" if ‘action’-file is same as actual file!
9 <?php
$fullname = $_POST ['fullname'] ; $age = $_POST ['age'] ; echo <<<END
<h4>The 'startform.php'-part</h4>
<form name="testform" method="post" action="" >
<table> <tr><td>Name:</td>
<td><input type="text" name="fullname" value="$fullname"/></td></tr> <tr><td>Age:</td>
<td><input type="text" name="age" value="$age"/></td></tr> <tr><td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Reset" />
<input type="button" value="Clear" onclick="clear_all();"/></td></tr> </table>
</form>
<script>document.testform.fullname.select(); </script> END;
?>
More functionality in one
single PHP-file… (cont. 2)
Content of ‘startform.php’:Different behavior at first time versus ‘at second time’!
10
3
# :
%4
<html><head><title>Test with isset(..)</title></head><body> <h3>Test with isset(variabele)</h3>
<formaction="http://.../TestWithIsset.php" method="post">
Give a number value: <input type="text" name="number"size="5" />
<p><input type="submit" value="Calculate square" />
</form><hr />
<?php
if ( isset( $_POST['number'] ) ) { $number = $_POST['number'] ;
echo "<h4>We received number = $number</h4>" ; $square = $number*$number ;
echo "Its square-value is: $square<br />" ;
echo "<formaction=\"http://.../TestWithIsset.php\" method=\"post\">\n"; echo "Give your firstname: <input type=\"text\" name=\"firstname\"/> " ; echo "<p><input type=\"submit\" value=\"Send name\" /></p>\n"; echo "</form><hr />" ;
}
elseif ( isset( $_POST['firstname'] ) ) { $firstname = $_POST['firstname'] ;
echo "<p>Hello $firstname, glad to see you!</p>" ; if ( !isset($_POST['number']) )
echo "In this part we don't know a variable 'number' " ; echo "<hr />" ; } ?> </body></html> ; < = 9 11
!
#1
>0 %
, -&- 8$query = "UPDATE Members SET Address = \"$Address\",
Cityname= \"$Cityname\" WHERE Membernr= \"$Membernr\" " ;
" !
? 7 #(+ @%
A >0 8 !
B C !
D ! >0 8
Syntax of the SQL-Update-command:
UPDATEtable_nameSETcolumn_name_1 = … , column_name_2= …
WHERE <conditie>
12
!
#1
>0 %
#
%
The SQL command for
deleting
data from a table is:
DELETE FROM
table_name
WHERE
<condition>
Do not forget the ‘WHERE’-part, because if omitted, the
whole table will be emptied… (all records in that table will be
deleted)!
13
2
E
, # % ! 3 !
4
extract -- Import variables into the current symbol table from an array
!9 ! 3 9 4 F #
8 % !
$membernr = $_POST [ 'membernr' ] ;
$amount = $_POST [ 'amount' ] ;
G extract ( $_POST ) ; ! $ # ! 2% C -&- ! 9 ! 5 1 >0 8 " 8 14
-&-<html><head><title>PHP-test on not Empty</title></head> <body>
<?php
function isEmpty ( $somevar ){ return ( strlen($somevar) == 0) ;
}
extract ( $_POST,EXTR_SKIP );// if there is a $_POST['firstname'], // we will get the associated $firstname
if ( !isset ( $firstname ) ){
echo "<form action=\"http://.../PHP/test.php\" method=\"POST\" >\n" ; echo "Give firstname: <input type=\"text\" name=\"firstname\"/>\n" ; echo "<p><input type=\"submit\" value=\"Submit to test on server\" /></p>\n" ; echo "</form>\n";
} else{
echo "We received: \$firstname = $firstname " ;
if ( isEmpty ( $firstname ) ) // test on server/side !!!
echo "<br />String is empty ... we shall NOT proceed ... " ;
else
echo "<br />String is not empty ... we may proceed..." ; } ?> </body></html> # -&- ! % 15
E
9
@
<html> <head><title>PHP-test on not Empty</title></head> <body>
<form action="http://localhost/b3/PHP/test.php" method="POST" > Give firstname: <input type="text" name="firstname" /> <p><input type="submit" value="Submit to test on server" /></p> </form>
</body></html> ?%
A%
B% <html> <head><title>PHP-test on not Empty</title></head> <body>
We received: $firstname = Alice <br />String is not empty ... we may proceed ...
</body></html>
<html> <head><title>PHP-test on not Empty</title></head> <body>
We received: $firstname =
<br />String is empty ... we shall NOT proceed ...
</body></html> H ! < #$ #: % = 9 ! " #-&- % # ! % ! # ! ! % ! ! ! 16
The PHP-function extract(…) + a warning!
This function is used to import variables from an array into the current symbol table. The function returns the number of variables extracted.
It takes an associative array var_arrayand treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to extract_typeand prefixparameters.
extract— Import variables into the current symbol table from an array
Syntax: intextract( array $var_array [, int $extract_type [, string $prefix ]] )
extract()also checks for collisions with existing variables in the symbol table. The way invalid/numeric keys and collisions are treated is determined by the extract_type. It can be one of the following values:
EXTR_OVERWRITE : If there is a collision, overwrite the existing variable.
EXTR_SKIP : If there is a collision, don't overwrite the existing variable.
….(and many more)
WarningDo not use extract()on untrusted data, like user-input ($_GET, ...). If you do, make sure you use one of the non-overwriting extract_typevalues such as EXTR_SKIP
17
The PHP-function extract(…) + a warning! (2)
Extract: A Word of CautionAs stressed in the PHP Manual, avoid using "extract" on the super global arrays ($_GET, $_POST etc).
Doing so has the same effect as having register_globalsswitched on and will result in security holes in your code.
If you absolutely have to do this then make sure that you pass configuration options to "extract" to ensure it doesn't overwrite existing variables by prepending a standard prefix to each variable as shown in the example below (or by skipping variables which already exist with option "EXTR_SKIP"):
extract ( $_POST, EXTR_SKIP ) ; extract ( $_GET, EXTR_SKIP ) ;
Another possible construction is:
foreach ($_POST as $key=>$value) {
if ( !isset( $$key ) ) { $$key = $value; }
} 18
More functionality in a single PHP-file,
including
server-side validation
<body> <div class="top"> <?php include "top.inc" ; ?> </div> <div class="main"> <?phpif ( ! isset ( $_POST ['fullname'] ) ) include 'startform.php' ; else { include 'phpfunctions.php' ; $errors = check_values ( ) ; if ( ! $errors =="" ) { include 'startform.php' ;
echo "<script> document.testform.age.select(); alert( '$errors' ) ;</script> " ;
} else include 'request.php' ; } ?> </div> </body></html>
19
More functionality …, including
server-side validation (cont.)
Content of the file phpfunctions.php:function check_values ( )
{
$fullname = $_POST ['fullname'] ; if( isTooShort ( $fullname ))
$errors = " - Name is too short!\\n" ; $errors = $errors . check_age_value ();
if ( !$errors == "" )
$errors = "Error(s):\\n" .$errors ;
return $errors ; }
?>
function isTooShort ( $somevar )
{
return ( strlen( $somevar ) <= 3 ) ; } <?php function check_age_value ( ) { $age = $_POST['age'] ; if ( !is_numeric($age) ) {
$errors = " - Age must be numeric!" ; return $errors ;
}
else if ( $age<0 || $age>100 ) {
$errors = " - Age must be between 0 and 100!"; return $errors ; } else return "" ; } 20
-&-
I !
6
• Again: anything you can do with regular expressions, can also be done by ‘just’ coding (in PHP, Javascript etc.), line after line, to get the same desired effect; so: you are not forced to use regular expressions …
• Functions (in PHP): – preg_match() – ereg() and eregi()
– ereg_replace() & eregi_replace() – split()
Regular expressions can also be used in PHP-programming
Example: how to verify a Canadianpostal code with a Regexp in PHP?
if ( ! preg_match("/^[a-z]\d[a-z] ?\d[a-z]\d$/i" , $postalcode))
{
echo "Your postal code has an incorrect format. " ; }
21
!
-&-• We can send mail simply via PHP scripts
– Built in function mail:
mail ($receiver, $subject, $message, $extras)
– All arguments are strings
• $extras allows additional information to be passed
– Ex: From, Cc, Bcc
– See mail.php and sendmail.php
– Also see mail() in the PHP manual
22
-&- ;
J ! J ; -&- ! #% K 5 ! #)/; "* )/ ; " ! *% J #% 230
E ! ! L ! , H ; L - ! ! E E E H I E 99 9 99 8 9 9 99 9 99 B 9 9 ! http://nl2.php.net/manual/en/reference.pcre.pattern.syntax.php 24!
M -&-
1
>0
!
N
9LL
25
!
M -&-
1
>0
#
%
!
Gebruik één scherm [althans in de ogen van een gebruiker], waarmee diverse operaties op een betaling uitgevoerd kunnen worden.Als je in het veld ‘Betalingnr’ een waarde invoert en op de ‘Zoek’-knop klikt, worden van de betreffende betaling de gegevens in de database opgezocht en getoond. (Ook de naam van het betreffende lid wordt opgezocht en ‘readonly’ getoond...) Als de gegevens getoond worden, dan kunnen desgewenst wijzigingen worden aangebracht en via de ‘Verander’-knop ter aanpassing naar de database worden gestuurd. Via ‘Verwijder’ zou [alleen!!] die betreffende betaling uit de database moeten worden verwijderd.
N.B. Je kunt uiteraard niet het ‘betalingnr’ van een bestaande betaling veranderen!