Interaction between HTML, PHP, and MySQL
Why databases?
World Wide Web (WWW) is not just a place to provide information. If you have something to share with people all over the world as a website. However, this is not an easy task. When the website grows, you may encounter the following problems:
The website contains too many things, so that visitors cannot get what they want quickly. This problem is fatal to a website to some extent.
Visitors want to provide you with information that must be saved for future use.
The above two problems can be solved through the database!
In the world of WWW, databases are everywhere. Like Yahoo! , Amazon, eBay, as small as a simple message board, you can see the use of the database. It can even be said that databases are the foundation of all advanced applications.
Why use PHP and MySQL?
As far as I know, almost all major commercial website databases are SQL-based. Among them, Oracle is the most popular. It is very powerful, and of course it is expensive. SQL is not an applicationProgramIs a language, short for Structured Query Language (Structured Query Language), used to operate and query databases.
In recent years, some companies have developedCodeThe most famous SQL application is MySQL. It is not just free, but it is not inferior to Oracle for Small and Medium-sized database applications.
To run MySQL on a website, you need a script language to interact with the database. In the past, Perl was the most popular. But now it seems that PHP is better. Don't ask me what is the difference between them ?? In the past, I used Perl, which also worked very well, but now everyone seems to like PHP. Of course, its popularity makes sense.
Required Software
This part of content was mentioned earlier in chinabyteArticle. Readers can refer to the article "setting local php development for Win98. I will not go into details here.
HTML and PHP
Prepared by: Yangmei compilation clicks in this article: 398
Let's take a look at how PHP works. Take a look at the following code:
<HTML>
<Body>
<? PHP
Print "Hello, world .";
?>
</Body>
</Html>
When you request this page, it will display "Hello, world" in the browser ".
As you can see, PHP scripts are embedded in HTML files. It uses "<? Start with "?> . In addition, we can even embed HTML tags in PHP scripts:
<? PHP
Print "<HTML> ";
Print "<body> ";
Print "Hello, world .";
Print "</body> ";
Print "
?>
The two methods achieve the same goal, and the results are the same. However, in some special cases, it is more convenient to select one of them.
Prints Statement of PHP
Prepared by: Yangmei compilation clicks in this article: 398
The simplest interaction between PHP and HTML is achieved through the print statement:
<? PHP
Print "Hello, world .";
?>
Print is the simplest and most commonly used function. It is used to display some text in a browser window. The echo function is similar to print, but you can use ", "To separate multiple content to be displayed, which makes it easier to display mixed string constants and variables.
Another printf function is used to format the output of numbers. A number can be used as an integer or displayed in scientific notation.
In these functions, the use of parentheses is different:
ECHO must not contain parentheses
Printf must have
Print availability
To display a string or number, you only need to keep the variable name or constant behind the print statement. However, if you want to display an array, is it written as follows:
Print $ myarray;
The output result is "array". php tells you that $ myarray is an array. This may be helpful when you are not sure whether a variable is an array, but now we want to see the array content.
You can use the implode function to convert an array into a string. It contains two parameters, the first is the array variable name, and the second is the separator of the array content. After the conversion is complete, the content of the array is linked by a separator to form a string:
$ Implodedarray = implode ($ myarray ,",");
Print $ implodedarray;
You can also use the array_walk function to display arrays. This function performs the same function operation on each content of the array. For example:
Function printelement ($ element)
{
Print ("$ element <p> ");
}
Array_walk ($ myarray, "printelement ");
How does PHP send data to MySQL?
Prepared by: Yangmei compilation clicks in this article: 398
You should have a better understanding of HTML forms. The following code is a simple HTML form:
<HTML>
<Body>
<Form action = submitform. php3 method = get>
Last name: <input type = text name = first_name size = 25 maxlength = 25>
Name: <input type = text name = last_name size = 25 maxlength = 25>
<P>
<Input type = submit>
</Form>
</Body>
</Html>
After you enter the data and press the submit button, this form will send the data to submitform. php3. The PHP script then processes the received data. The following is the submitform. php3 code:
<HTML>
<Body>
<? PHP
Mysql_connect (localhost, username, password );
Mysql_select_db (dbname );
Mysql_query ("insert into tablename (first_name, last_name)
Values ('$ first_name', '$ last_name ')
");
Print ($ first_name );
Print ("");
Print ($ last_name );
Print ("<p> ");
Print ("thank you for entering the Registry ");
?>
</Body>
</Html>
In the third line of the Code, "username" and "password" represent the account and password for logging on to the MySQL database respectively. "Dbname" in the fifth line indicates the name of the MySQL database. "Tablename" in row 13th is the name of a data table in the database.
After you press submit, you can see that the name you entered is displayed in a new page. Let's take a look at the URL bar of the browser. Its content should be like this:
... /Submitform. php3? First_name = Fred & last_name = Flintstone
Because we use the form get method, data is transmitted to submitform. php3 through URL. Obviously, the get method has limitations. When there is a lot of content to be passed, you cannot use get, but you can only use POST method. However, no matter what method is used, after data transmission is complete, PHP automatically creates a variable with the same name (name attribute of the form) for the fields in each form.
PHP variables start with a dollar sign. the $ first_name and $ last_name variables are generated during php3 script processing. The content of the variables is what you input.
Let's check whether the name you entered is actually input into the database. Start MySQL and enter:
Mysql> select * From tablename;
You should be able to get a table with the content you just entered:
+ ------------ +
| First_name | last_name |
+ ------------ +
| Liu | ruifeng
+ ------------ +
1 rows in SET (0.00 Sec)
Let's analyze how submitform. php3 works:
The first two lines of the script are:
Mysql_connect (localhost, username, password );
Mysql_select_db (dbname );
The two function calls are used to open the MySQL database. The specific parameter meanings have been mentioned just now.
The following line executes an SQL statement:
Mysql_query ("insert into tablename (first_name, last_name)
Values ('$ first_name', '$ last_name ')
");
The mysql_query function is used to execute an SQL query for the selected database. You can execute any SQL statement in the mysql_query function. The executed SQL statement must be enclosed in double quotation marks as a string, and the variables must be enclosed in single quotation marks.
One thing to note: the MySQL statement should end with a semicolon (;). The same applies to a line of PHP code, but the MySQL statement in the PHP script cannot contain a semicolon. That is to say, when you enter the MySQL command at the mysql> prompt, you should add a semicolon:
Insert into tablename (first_name, last_name)
Values ('$ first_name', '$ last_name ');
However, if this command appears in a PHP script, remove the semicolon. This is because some statements, such as select and insert, can work with or without semicolons. However, there are still some statements, such as update, which won't work if you add a semicolon. To avoid trouble, remember this rule.
How PHP extracts data from MySQL
Now we create another HTML form to execute this task:
<HTML>
<Body>
<Form action = searchform. php3 method = get>
Enter your query content:
<P>
Last name: <input type = text name = first_name size = 25 maxlength = 25>
<P>
Name: <input type = text name = last_name size = 25 maxlength = 25>
<P>
<Input type = submit>
</Form>
</Body>
</Html>
Similarly, we need a PHP script to process this form. We will create another searchform. php3 file:
<HTML>
<Body>
<? PHP
Mysql_connect (localhost, username, password );
Mysql_select_db (dbname );
If ($ first_name = "")
{$ First_name = '% ';}
If ($ last_name = "")
{$ Last_name = '% ';}
$ Result = mysql_query ("select * From tablename
Where first_name like '$ first_name %'
And last_name like '$ last_name %'
");
If ($ ROW = mysql_fetch_array ($ result )){
Do {
Print $ row ["first_name"];
Print ("");
Print $ row ["last_name"];
Print ("<p> ");
} While ($ ROW = mysql_fetch_array ($ result ));
} Else {print "sorry, no matching record found in our database. ";}
?>
</Body>
</Html>
After you enter the content to be retrieved in the form and then press the submit button, a new page is displayed, listing all matching search results. Next let's take a look at how this script completes the search task.
The preceding statements are the same as described above. First, a database connection is established, and then a database and a data table are selected. These are required for each database application. Then there are several statements:
If ($ first_name = "")
{$ First_name = '% ';}
If ($ last_name = "")
{$ Last_name = '% ';}
These rows are used to check whether the fields in the form are empty. Note that the two equal signs, because most PHP syntax comes from the C language. Here the equal signs are used in the same way as C: an equal sign is a value assignment, and two equal signs represent logical equals. It should also be noted that when the condition after if is true, the following statements to be executed are placed in "{" and, in addition, each statement must be followed by a semicolon to end the statement.
Percent sign % is a wildcard in the SQL language. After understanding it, you should know the meaning of the two rows: if the "first_name" field is blank, all first_name will be listed. The following two sentences also mean the same.
$ Result = mysql_query ("select * From tablename
Where first_name like '$ first_name %'
And last_name like '$ last_name % '"
");
This line completes most of the search work. After the mysql_query function completes a query, it returns an integer sign.
The query selects records from all records that have the same first_name and $ first_name variables, and the last_name column and $ last_name variable values, and puts them in the saved record set, use the returned Integer as the flag of this record set.
If ($ ROW = mysql_fetch_array ($ result )){
Do {
Print $ row ["first_name"];
Print ("");
Print $ row ["last_name"];
Print ("<p> ");
} While ($ ROW = mysql_fetch_array ($ result ));
} Else {print "sorry, no matching record found in our database. ";}
This is the last step, that is, the display part. The mysql_fetch_array function extracts the content of the first row of the query result and displays it in print statements. The parameter of this function is the integer sign returned by the mysql_query function. After mysql_fetch_array is successfully executed, the record set pointer will be automatically moved down, so when mysql_fetch_array is executed again, the content of the next record will be obtained.
The array variable $ row is created by the mysql_fetch_array function and filled with the query result field. Each component of the array corresponds to each field in the query result.
If a matching record is found and the variable $ row is not empty, the statement in curly brackets is executed:
Do {
Print $ row ["first_name"];
Print ("");
Print $ row ["last_name"];
Print ("<p> ");
} While ($ ROW = mysql_fetch_array ($ result ));
This is a do... While loop. Unlike the while loop, it executes the loop body once first, and then checks whether the loop conditions are met. As we already know that when the record set is not empty, we must at least execute the loop body. So we should use do... While instead of while loop. In curly braces, it is the body of the loop to be executed:
Print $ row ["fir
How PHP extracts data from MySQL
Prepared by: Yangmei compilation clicks in this article: 398
Now we create another HTML form to execute this task:
<HTML>
<Body>
<Form action = searchform. php3 method = get>
Enter your query content:
<P>
Last name: <input type = text name = first_name size = 25 maxlength = 25>
<P>
Name: <input type = text name = last_name size = 25 maxlength = 25>
<P>
<Input type = submit>
</Form>
</Body>
</Html>
Similarly, we need a PHP script to process this form. We will create another searchform. php3 file:
<HTML>
<Body>
<? PHP
Mysql_connect (localhost, username, password );
Mysql_select_db (dbname );
If ($ first_name = "")
{$ First_name = '% ';}
If ($ last_name = "")
{$ Last_name = '% ';}
$ Result = mysql_query ("select * From tablename
Where first_name like '$ first_name %'
And last_name like '$ last_name %'
");
If ($ ROW = mysql_fetch_array ($ result )){
Do {
Print $ row ["first_name"];
Print ("");
Print $ row ["last_name"];
Print ("<p> ");
} While ($ ROW = mysql_fetch_array ($ result ));
} Else {print "sorry, no matching record found in our database. ";}
?>
</Body>
</Html>
After you enter the content to be retrieved in the form and then press the submit button, a new page is displayed, listing all matching search results. Next let's take a look at how this script completes the search task.
The preceding statements are the same as described above. First, a database connection is established, and then a database and a data table are selected. These are required for each database application. Then there are several statements:
If ($ first_name = "")
{$ First_name = '% ';}
If ($ last_name = "")
{$ Last_name = '% ';}
These rows are used to check whether the fields in the form are empty. Note that the two equal signs, because most PHP syntax comes from the C language. Here the equal signs are used in the same way as C: an equal sign is a value assignment, and two equal signs represent logical equals. It should also be noted that when the condition after if is true, the following statements to be executed are placed in "{" and, in addition, each statement must be followed by a semicolon to end the statement.
Percent sign % is a wildcard in the SQL language. After understanding it, you should know the meaning of the two rows: if the "first_name" field is blank, all first_name will be listed. The following two sentences also mean the same.
$ Result = mysql_query ("select * From tablename
Where first_name like '$ first_name %'
And last_name like '$ last_name % '"
");
This line completes most of the search work. After the mysql_query function completes a query, it returns an integer sign.
The query selects records from all records that have the same first_name and $ first_name variables, and the last_name column and $ last_name variable values, and puts them in the saved record set, use the returned Integer as the flag of this record set.
If ($ ROW = mysql_fetch_array ($ result )){
Do {
Print $ row ["first_name"];
Print ("");
Print $ row ["last_name"];
Print ("<p> ");
} While ($ ROW = mysql_fetch_array ($ result ));
} Else {print "sorry, no matching record found in our database. ";}
This is the last step, that is, the display part. The mysql_fetch_array function extracts the content of the first row of the query result and displays it in print statements. The parameter of this function is the integer sign returned by the mysql_query function. After mysql_fetch_array is successfully executed, the record set pointer will be automatically moved down, so when mysql_fetch_array is executed again, the content of the next record will be obtained.
The array variable $ row is created by the mysql_fetch_array function and filled with the query result field. Each component of the array corresponds to each field in the query result.
If a matching record is found and the variable $ row is not empty, the statement in curly brackets is executed:
Do {
Print $ row ["first_name"];
Print ("");
Print $ row ["last_name"];
Print ("<p> ");
} While ($ ROW = mysql_fetch_array ($ result ));
This is a do... While loop. Unlike the while loop, it executes the loop body once first, and then checks whether the loop conditions are met. As we already know that when the record set is not empty, we must at least execute the loop body. So we should use do... While instead of while loop. In curly braces, it is the body of the loop to be executed:
Print $ row ["first_name"];
Print ("");
Print $ row ["last_name"];
Print ("<p> ");
Then, check whether the while condition is met. The mysql_fetch_array function is called again to obtain the content of the current record. This process continues cyclically. If no record exists, mysql_fetch_array returns false. When the loop ends, the record set is completely traversed.
The array returned by mysql_fetch_array ($ result) can be called by field names or subscripts to reference each component of the array, just like an ordinary array. In this way, the above Code can also be written as follows:
Print $ row [0];
Print ("");
Print $ row [1];
Print ("<p> ");
We can also use the echo function to compact these four statements:
Echo $ row [0], "", $ row [1], "<p> ";
When no matching record is found, no content exists in $ row. In this case, the else clause of the IF statement is called:
Else {print "sorry, no matching record found in our database. ";}
Check whether the query is normal
Prepared by: Yangmei compilation clicks in this article: 398
Can your select, delete, or other queries work properly? This must be clarified, and never draw conclusions easily.
It is easier to check an insert query:
$ Result = mysql_query ("insert into tablename (first_name, last_name)
Values ('$ first_name', '$ last_name ')
");
If (! $ Result)
{
Echo "<B> insert query failed: </B>", mysql_error ();
Exit;
}
However, this check method does not work for select queries. In this case, we should do the following:
$ Selectresult = mysql_query ("select * From tablename
Where first_name = '$ first_name'
And last_name = '$ last_name'
");
If (mysql_num_rows ($ selectresult) = 1)
{
Print "SELECT query successful. ";
}
Elseif (mysql_num_rows ($ selectresult) = 0)
{
Print "SELECT query failed. ";
Exit;
}
The delete query should be like this:
$ Deleteresult = mysql_query ("delete from tablename
Where first_name = '$ first_name'
And last_name = '$ last_name'
");
If (mysql_affected_rows ($ deleteresult) = 1)
{
Print "delete query succeeded ";
}
Elseif (mysql_affected_rows ($ deleteresult )! = 1)
{
Print "delete query failed ";
Exit;
}