SoFunction
Updated on 2025-04-09

A good basic PHP study notes

1. Four forms of representation of PHP fragments.
Standard tags: <?php                    >
short tags: <?
asp tags: <%                                                                                                                                                                                                                                                         �
script tags:<script language=”php”></script>
2. PHP variables and data types
1) $variable, variable starts with letters and _, and cannot have spaces
2)          Assign $variable=value;
3) Weak type, direct assignment, no need to display declared data types
4) Basic data types: Integer, Double, String, Boolean, Object (object or class), Array (array)
5) Special data types: Resourse (reference to third-party resources (such as databases)), Null (empty, uninitialized variable)
3. Operator
1)          Assign operator:=
2) Arithmetic operators: +, -, *, /, % (module)
3) Connection operator:., No matter what the operand is, it is regarded as a String, and the result returns String
4) Combined Assignment Operators Total Assignment Operators: +=, *=, /=, -=, %=, .=
5)           Automatically Incrementing and Decrementing Automatically increase and decrease operators:
(1) $variable+=1 <=>$variable++; $variable-=1 <=>$variable-, just like C language, do other operations first, then ++ or -
(2) ++$variable, -$variable, ++ or - first, then do other operations
6)         Comparison operator: == (the left side is equal to the right side),! = (the left side is not equal to the right), = == (the left side is equal to the right, and the data type is the same), >=, >, <, <=
7)        Logical operators: || ó or, &&óand, xor (when there is only one of the left and right sides is true, return true),!
4. Comments:
Single line comments://, #
Multi-line comment: /* */
5. Each statement ends with a ; number, the same as Java
6. Define constants: define("CONSTANS_NAME", value)
7. Print statement: print, same as C language
8. Process control statements
1)           if statement:
(1)if(expression)
{
//code to excute if expression evaluates to true
}
(2)if(expression)
{
}
else
{
}
(3)if(expression1)
{
}
elseif(expression2)
{
}
else
{
}
2)           Switch statement
switch ( expression )
{
case result
// execute this if expression results in result1
break;
case result
// execute this if expression results in result2
break;
default:
// execute this if no break statement
// has been encountered hitherto
}
3)       ? Operator:
( expression )?returned_if_expression_is_true:returned_if_expression_is_false;
4)           while statement:
(1) while ( expression ) 
{
              // do something
}
(2)do
{
// code to be executed
} while ( expression );
5)          for statement:
for ( initialization expression; test expression; modification expression ) {
// code to be executed
}
6)        break;continue
9. Write functions
1)          Definition of the function:
function function_name($argument1,$argument2,…) //Formal parameters
{
//function code here;
}
2) Function calls
function_name($argument1,$argument2,...); //Formal parameters
3) Dynamic Function Calls:
<html>
<head>
<title>Listing 6.5</title>
</head>
<body>
<?php
function sayHello() {   //Define the function saysHello
print "hello<br>";
}
$function_holder = "sayHello";  // Assign the function name to the variable $function_holder
$function_holder();  //The variable $function_holder becomes a reference to the function sayHello. Calling $function_holder() is equivalent to calling sayHello
?>
</body>
</html>
4) Variable scope:
Global variables:
<html>
<head>
<title>Listing 6.8</title>
</head>
<body>
<?php
$life=42;
function meaningOfLife() {
global $life;
/*Redeclare $life as a global variable here. Accessing the global variable inside the function must be like this. If the value of the variable is changed within the function, it will be changed in all code snippets*/
print "The meaning of life is $life<br>";
}
meaningOfLife();
?>
</body>
</html>
5)        Use static
<html>
<head>
<title>Listing 6.10</title>
</head>
<body>
<?php
function numberedHeading( $txt ) {
static $num_of_calls = 0;
$num_of_calls++;
print "<h1>$num_of_calls. $txt</h1>";
}
numberedHeading("Widgets");  // When the first call is called, the $num_of_calls value is 1 printed
print("We build a fine range of widgets<p>");
numberedHeading("Doodads");  /* When the first call is called, the $num_of_calls value is 2, because the variable is static, and static is resident memory*/
print("Finest in the world<p>");
?>
</body>
</html>
6)
Pass the value: function function_name($argument)
<html>
<head>
<title>Listing 6.13</title>
</head>
<body>
<?php
function addFive( $num ) {
$num += 5;
}
$orignum = 10;
addFive( &$orignum );
print( $orignum );
?>
</body>
</html>
Results: 10
Transmission address: funciton function_name(&$argument)
<html>
<head>
<title>Listing 6.14</title>
</head>
<body>
<?php
function addFive( &$num ) {
$num += 5;  /*What is passed is a reference to the variable $num, so changing the value of the formal parameter $num is to really change the value saved in the physical memory of the variable $orignum*/
}
$orignum = 10;
addFive( $orignum );
print( $orignum );
?>
</body>
</html>
Results: 15
7)          Create anonymous function: create_function('string1','string2');  create_function is a built-in PHP function, specifically used to create anonymous functions, accepting two string-type parameters, the first is the parameter list, and the second is the body of the function
<html>
<head>
<title>Listing 6.15</title>
</head>
<body>
<?php
$my_anon = create_function( '$a, $b', 'return $a+$b;' );
print $my_anon( 3, 9 );
// prints 12
?>
</body>
</html>
8)
10. Connect to MySQL using PHP
1)        Connection: &conn=mysql_connect("localhost", "joeuser", "somepass");
2)        Close the connection: mysql_close($conn);
3) Establish connection between the database and the connection: mysql_select_db(database name, connection index);
4) Execute the SQL statement to MySQL: $result = mysql_query($sql, $conn); //Addition and deletion, modification and search are all the sentences
5) Retrieve data: Return the number of records: $number_of_rows = mysql_num_rows($result);
Put the record into an array: $newArray = mysql_fetch_array($result);
example:
   <?php
   // open the connection
   $conn = mysql_connect("localhost", "joeuser", "somepass");
   // pick the database to use
   mysql_select_db("testDB",$conn);
   // create the SQL statement
   $sql = "SELECT * FROM testTable";
   // execute the SQL statement
   $result = mysql_query($sql, $conn) or die(mysql_error());
  //go through each row in the result set and display data
  while ($newArray = mysql_fetch_array($result)) {
      // give a name to the fields
      $id = $newArray['id'];
      $testField = $newArray['testField'];
      //echo the results onscreen
      echo "The ID is $id and the text is $testField <br>";
  }
  ?>
11. Accept form elements: $_POST [form element name],
For example, <input type=text  name=user>ó$_POST[user]
Accept the queryString median value in the url (GET method): $_GET[queryString]
12. Turn to other pages: header("Location: ");
13. String operation:
1)Explode("-",str) split in Java
2) str_replace($str1,$str2,$str3) =>$str1 to search for string, the string used for substitution by $str2, $str3 starts looking for substitution from this string
3)substr_replace:
14、session:
1) Open session: session_start(); //You can also set session_auto_start=1. You don’t have to write this sentence for every script anymore, but the default is 0, so you must write it.
2) Assign value to session: $_SESSION[session_variable_name]=$variable;
3) Access session: $variable = $_SESSION[session_variable_name];
4) Destroy session: session_destroy();
15. Complete example of displaying classification:
<?php
//connect to database
$conn = mysql_connect("localhost", "joeuser", "somepass")
or die(mysql_error());
mysql_select_db("testDB",$conn) or die(mysql_error());
$display_block = "<h1>My Categories</h1>
<P>Select a category to see its items.</p>";
//show categories first
$get_cats = "select id, cat_title, cat_desc from
store_categories order by cat_title";
$get_cats_res = mysql_query($get_cats) or die(mysql_error());
if (mysql_num_rows($get_cats_res) < 1) { //If the number of rows returned is less than 1, it means there is no classification
$display_block = "<P><em>Sorry, no categories to browse.</em></p>";
} else {
while ($cats = mysql_fetch_array($get_cats_res)) { //Put the record into the variable $cats
$cat_id = $cats[id];
$cat_title = strtoupper(stripslashes($cats[cat_title]));
$cat_desc = stripslashes($cats[cat_desc]);
$display_block .= "<p><strong><a
href="$_SERVER[PHP_SELF][U1] ?cat_id=$cat_id">$cat_title</a></strong>//Click this url to refresh this page. Read cat_id on line 28 to display the entries of the corresponding classification.
<br>$cat_desc</p>";
if ($_GET[cat_id] == $cat_id) { //Select a category and look at the following entry
//get items
$get_items = "select id, item_title, item_price
from store_items where cat_id = $cat_id
order by item_title";
$get_items_res = mysql_query($get_items) or die(mysql_error());
if (mysql_num_rows($get_items_res) < 1) {
$display_block = "<P><em>Sorry, no items in
this category.</em></p>";
} else {
$display_block .= "<ul>";
while ($items = mysql_fetch_array($get_items_res)) {
$item_id = $items[id];
$item_title = stripslashes($items[item_title]);
$item_price = $items[item_price];
$display_block .= "<li><a
href="?item_id=$item_id">$item_title</a>
</strong> ($$item_price)";
[U2]                   }
$display_block .= "</ul>";
}
}
}
}
?>
<HTML>
<HEAD>
<TITLE>My Categories</TITLE>
</HEAD>
<BODY>
<? print $display_block; ?>
</BODY>
</HTML>
16. PHP connection Access:
<?  
$dbc=new com("");  
$dbc->open("driver=microsoft access driver (*.mdb);dbq=c:");  
$rs=$dbc->execute("select * from tablename");  
$i=0;  
while (!$rs->eof){  
$i+=1  
$fld0=$rs->fields["UserName"];  
$fld0=$rs->fields["Password"]; 
....  
echo "$fld0->value $fld1->value ....";  
$rs->movenext();  
}  
$rs->close();  
?>