PHP Syntax

advertisement
1
Coms 463 Presentation
Programming with PHP
By: Seth Larson
2
A little bit about PHP.
PHP is an acronym for Hypertext Preprocessor. PHP is a general purpose server
side scripting language that is used in web development. PHP supports many
different databases like MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL,
Generic ODBC, etc. The best thing about PHP is it is open source software, so it is
free. The link to the download is http://www.php.net. PHP files have file
extension of ".php", ".php3", or ".phtml"
What do you need installed on your computer to use php?
To use PHP on your computer you need a server that supports PHP. Some servers
that have the support are Apache(open source), IIS (Microsoft), and Oracle. The
latest version of PHP can be found at http://www.php.net.
You can test if you already have support for PHP with the
code on the right. Copy and paste it in notepad and then
save to “C:\Inetpub\wwwroot” with the filename
“phpinfo.php”. Type http://localhost/phpinfo in a browser
and the screen will look like the “phpinfo.php example”
located at the end of the paper. If you get an error or
don’t see anything your PHP is not working. The webpage
will have all the information about your php configuration.
<html>
<body>
<?php
phpinfo();
?>
</body>
</html>
PHP scripts run on the server-side and are sent to the client in html form. The
sever-side PHP script itself is embedded directly in the HTML. Likewise, you can
embed HTML in the PHP script shown in below. The example prints “PHP rules”
inside a HTML table. Echo is a print call in PHP.
<html>
<body>
<?php echo "<table border=1>
<tr><td>
<p>PHP rules!</p>
</td></tr>
</table>"
?>
</body>
</html>
If you view the page source you will see that the server sent all the code in html
which looks like this.
<html>
<body>
<table border=1>
<tr><td>
<p>PHP rules!</p>
</td></tr>
</table>
</body>
</html>
3
PHP Syntax
All PHP scripting blocks begin with the tag “<?php” and ends with “?>” and can be
placed anywhere in html. PHP statements always end with a semicolon.
PHP variables
Variables are easy to create with PHP. Just like in other high-level languages
there are syntax rules. Some predefined variables as well as predefined functions
exist like echo, $GLOBALS, and $POST, php is no different. Variables in PHP have
to start with “$” followed by a name, example $variable_name.
The code just below shows how to concatenate variables and also how to use the
“\” character to print the name of a variable. The first php block shows how to use
the “\” character. The character needs to be directly in front of the variable
name, this tells the server to print what directly follows and not to treat it as a
variable.
<html>
<body>
<?php
$var_A = " Print \$var_A ";
$var_B = "To print a variable name instead of what the
variable is holding use the \ character.";
echo $var_B;
echo"<P>";
echo $var_A;
?>
</body>
</html>
The following code shows how to use the (.) dot operator to concatenate the
var_C and var_D variables. The code shows how to use a forward slash followed
by a asterisk (“/*”) and then an asterisk followed by a forward slash (“*/”) for a
block comment A single line comment syntax is double forward slashes (“//”)
followed by the comment.
<html>
<body>
<?php
/*
You can use a Block Comment
*/
// or you can use this to comment.
$var_C = "concatenation is done with a";
$var_D = "(.) dot operator";
echo $var_C.$var_D;
?>
</body>
</html>
4
PHP operators
Operators, conditionals, and looping are the same as other high level languages
 Arithmetic Operators
+, -, /, *
 Assignment Operators
=, +=, -=, *=, /=, %=
 Comparison Operators
==, !=, >, <, >=, <=
 Logical Operators
&&, ||, !

If – else statement
if (condition)
code to be executed
else
code to be executed

While
while
{
code to be executed;
}

Do-while
do
{
code to be executed;
}
while (condition);


For
Foreach
PHP and HTML Forms
PHP automatically puts the HTML form elements in a global array labeled $_POST.
Retrieving an element variable can be done by using the predefined variable
$_POST[“element name”]. Just a note that if your form’s method is not “post”
and instead is “get”, then the variables are available with the predefined variable
$_GET [“element name”].
The following code is a html form with 3 textboxes, “Your Id”, “Your First Name “,
and “Your Last Name.” There is a checkbox with the value “male” and one with the
value “female”. The last element in the form is a submit button.
<html>
<body>
<form action="php_forms_next.php" method="post">
<pre>Your Id: <input type = "text" name = "id"/></ br>
Your First name: <input type="text" name="first" /></ br>
Your Last name: <input type="text" name="last" />
<?php
echo "male: <input type = checkbox name = sex value = male>
Female: <input type = checkbox name= sex value =female
?>
5
<input type="submit" /></pre>
</form>
</body>
</html>
Once the submit button is clicked the page is redirected to php_forms_next.php
and the variables are added to the global array $POST. The code below prints the
user entered variables from the form. $_POST[“element name”] is used to
retrieve the form variables. Again I used the $POST variable because the
previous page’s form method is “post”.
<html>
<body><pre>You said your Id number was:
<?php echo $_POST["id"]; ?></pre>
<pre>You said your First name was
<?php echo $_POST["first"]; ?></pre>
<pre>You said you Last name was
<?php echo $_POST["last"]; ?></ pre>
<pre>You also said you are
<?php echo $_POST["sex"];?></pre>
<pre>Your favorite color is
<?php echo $_POST["color"];?></pre>
</body>
</html>
PHP and Text Files
To open a file use the fopen () function. The syntax for the file open function is
“fopen (“filename to open”, “mode to open file”).”
The file can be
o
o
o
o
o
o
opened in different modes
Read only (r)
Read / write (r+ or w+)
Write (w)
Append (a)
Read/Append (a+)
Create (x)
Sample code to the right was taken from
http://www.w3schools.com. The code
first checks if the specified file can be
opened with the mode requested. If not
a prompt alerting the error is printed.
Once open the file reads one character at
a time and prints it. After reading the file,
the file is closed.
<html>
<body>
<?php
if (!($file=fopen("php_file.txt","r")))
exit("Can’t open file.");
while (!feof($file))
{
$char=fgetc($file);
echo $char;
}
//$write = fputs($fp, “write hi”);
fclose($file);
?>
</body>
</html>
6
PHP and MySQL database use:
PHP supports many different databases like MySQL, Informix, Oracle, Sybase,
Solid, PostgreSQL, Generic ODBC, etc. The code below works with “mydb,” a
database created with MySQL. Mydb has 3 columns including “Id”, “First Name”,
“Last Name.” MySQL is also open-source software. The sample code in this paper
uses a MySQL database and PHP has predefined functions for use with MySQL.
Read from a MySQL database.
The code below connects to the MySQL database “mydb” and prints the first name
column from each record.
The first step is to connect to the database and the mysql_connect () function.
The syntax for the function is mysql_connect("server address", "username",
"password"). By default the database user name is “root.” Once connected to the
MySQL server the database to use has to be selected. This is done using
mysql_select_db ("database name", $db). $db being the label given to the
mysql_connect () function. The next step is to send a query to the “mydb”
database with mysql_query (). The syntax is mysql_query(“sql statement”). The
result of the query is held at the label $result. The “first name” column of each
record is printed. Last the connection to “mydb” is closed.
 %s indicates that the variable in the second half of the expression (e.g.,
mysql_result($result,$i,"first")) should be treated as a string and printed.
<html>
<body>
<?php
$db = mysql_connect("localhost", "root", "seth");
mysql_select_db("mydb", $db);
$result = mysql_query("SELECT * FROM employee" ,$db);
$count=mysql_numrows($result);
$i=0;
while ($i < $count)
{
printf("First Name: %s", mysql_result($result,$i,"first"));
echo "<p>";
$i++;
}
mysql_close();
?>
</body>
</html>
The following sample code reads a database query one record at a time and displays
the output in a HTMl table. The same steps are followed as above. First connect to
MySQL, then select a database to use, send a SQL query and print the records inside
a table. There are two columns in the table outputted. The first column holds the
database column “id” and the second table column “First and Last Name” holds the
database columns “First Name” and “Last Name”. In the while loop you see multiple
$myrow[] variable calls. This is because $myrow holds the record from the
database as an array. The use of myrow[0] gets the first variable in the array.
<html>
7
<body>
<?php
$db = mysql_connect("localhost", "root", "seth");
mysql_select_db("mydb",$db);
$result = mysql_query("SELECT * FROM employee",$db);
echo "<table border=1>\n";
echo "<tr><td>id</td><td>First Name and Last Name</td></tr>\n";
while ($myrow = mysql_fetch_row($result))
{
printf("<tr><td>%s </td><td>%s %s</td></tr>\n",
$myrow[0], $myrow[1], $myrow[2]);
}
echo "</table>\n";
?>
</body>
</html>
Insert into a MySQL database.
The sample code below is a HTML form that the user enters an id, first name, and last
name into textboxes. The user entered variables are inserted into the “mydb” database
when the submit button is clicked.
<html>
<body>
<form action="php_insert_form_insert.php" method="post">
<pre>
Your Id:
<input type = "text" name = "id"/>
Your First name: <input type="text" name="first" />
Your Last name: <input type="text" name="last" />
</br>
<input type="submit" /></pre>
</form>
</body>
</html>
To insert in a MySQL database you follow the same steps demonstrated twice in the sample
codes above. Once connected the SQL query statement has to follow the syntax for a insert
statement. The insert query below is $query = mysql_query(INSERT INTO employee
VALUES ('$id','$first','$last'));. After an insert has been made the code prints each
record in the database.
<html>
<body>
<?php
$id = $_POST["id"];
$first = $_POST["first"];
$last = $_POST["last"];
$db = mysql_connect("localhost", "root","seth");
mysql_select_db("mydb",$db);
$query = "INSERT INTO employee VALUES ('$id','$first','$last')";
mysql_query($query);
$result = mysql_query("SELECT * FROM employee",$db);
echo "<table border=1>\n";
8
echo "<tr><td>id</td><td>First Name and Last Name</td></tr>\n";
while ($myrow = mysql_fetch_row($result))
{
printf("<tr><td>%s </td><td>%s %s</td></tr>\n",
$myrow[0], $myrow[1], $myrow[2]);
}
echo "</table>\n";
?>
</body>
</html>
9
Phpinfo.php example
Resources:
http://www.w3schools.com
http://www.php.net
http://hotwired.lycos.com/webmonkey/programming/php/tutorials/tutorial4.html
http://www.free2code.net/plugins/articles/read.php?id=84
10
Short answer.
1. What does php stand for?
Answer: hypertext preprocessor
2. What character do all php variables start with?
Answer: they all start with “$”
3. What is one server that supports php?
Answer: Apache, IIS, oracle
4. There are two basic ways to print in Php, what are they?
Answer: print and echo
5. Is php a server side or client side scripting language?
Answer: server side
Multiple choice.
1. Once a php “post” form is submitted where are the element variables automatically
created?
A. $_POST
B. $_GET
2. What will the output of this code be.
<?php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2 ;
?>
A. Hello World
B. 1234
C. Hello World 1234
3. Php code is inside a wrapper that starts <?php and ends with ?>
A. true
B. false
4. Can you use if- else and while statements in PHP?
Answer: yes
5. Php operators, conditionals, and looping are the same as other high level languages.
A. true
B. false
Fill in the blank.
1. Free code that anyone can download and use is called ________ ________ code?
Answer. Open source
2. __ is used to concatenate in php?
11
Answer: you use a period (“.”)
3. Php statements end with a ___?
Answer: a semicolon (“;”)
4. Php statements be put __________ in html code.
Answer: anywhere
5. Php scripting blocks start with <____ and end with __>?
Answer: ?php and ?
Download