How to send data to MySQL in PHP

Source: Internet
Author: User
Tags mysql in php tutorial php3 file
How to send data to MySQL in PHP

You should be familiar with HTML forms, the following piece of code is a very 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>


When you enter data and press the Submit button, the form will send the data to SUBMITFORM.PHP3. With this PHP script to process the received data, here is the code for SUBMITFORM.PHP3:

< 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 completing the registration form");

?>

</body>


The "username" and "password" in the third line of the code represent the account number and password you log in to the MySQL database respectively. The "dbname" in line fifth represents the name of the MySQL database. In line 13th, "TableName" is the name of a data table in the database.

When you press submit, you can see that the name you entered is displayed in a new page. Take a look at the browser's URL bar, its contents should be like this:

.../submitform.php3?first_name=fred&last_name=flintstone

Because we're using the form GET method, the data is routed to Submitform.php3 via a URL. Obviously, the Get method is limited, when you want to pass a lot of content, you can not use GET, can only use the POST method. But no matter what the method, when the data transfer is complete, PHP automatically creates a variable with the same name (the Name property of the form) for each field in the form.

PHP variables have been started with a dollar sign, so that in the process of SUBMITFORM.PHP3 script processing, there will be $first _name and $last _name These two variables, the content of the variable is what you enter.

Let's check to see if the name you entered is actually entered in the database. To start MySQL, at the mysql> prompt, enter:

Mysql> SELECT * FROM TableName;

You should be able to get a table with the content that you just typed:

+------------+------------+

| first_name | last_name |

+------------+------------+

| Willow | such as wind

+------------+------------+

1 rows in Set (0.00 sec)

Let's examine how SUBMITFORM.PHP3 works:

The first two lines of the script are:

mysql_connect (localhost, username, password);



mysql_select_db (dbname);

These two function calls are used to open the MySQL database, the meaning of the specific parameters has just been said.

The following line is the execution of 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 against 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, in which the variable is enclosed in single quotation marks.

One thing to be aware of: MySQL's statement is to use a semicolon (;) At the end, the same is true for a single line of PHP code, but the MySQL statement in a PHP script cannot have a semicolon. In other words, 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 ');

But if the command appears in a PHP script, remove the semicolon. This is done because some statements, such as SELECT and INSERT, have no semicolons to work with. However, there are some statements, such as UPDATE, with a semicolon. In order to avoid trouble, it is good to remember this rule.

How PHP extracts data from MySQL

Now let's create another HTML form to perform this task:

< html>

< body>

< form action=searchform.php3 Method=get>

Please input your inquiry 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>


Also, there is a PHP script to process this form, and we'll build a 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 record is found in our database. ";}

?>

</body>


When you enter what you want to retrieve in the form, and then press the SUBMIT button, a new page is entered that lists all the matching search results. Let's take a look at how this script completes the search task.

The preceding statements, like the one above, first establish a database connection and then select the database and data tables, which are required for each database application. Then there are several statements:

if ($first _name = = "")

{$first _name = '% ';}

if ($last _name = = "")

{$last _name = '% ';}

These lines are used to check that the fields of the form are empty. Note that the two equals sign, because PHP's syntax is mostly derived from the C language, where the use of equal sign is the same as C: An equal sign is an assignment number, two equals equal to the logical equals. It should also be noted that when the if post-condition is true, the statements to be executed later are placed in "{" and "}", and each of these statements is followed by a semicolon to indicate the end of the statement.

Percent percent is the wildcard character of the SQL language, and when you understand it, you should know what the two lines mean: If the "first_name" field is empty, all first_name will be listed. The following two sentences also mean the same thing.

$result = mysql_query ("SELECT * FROM tablename

WHERE first_name like ' $first _name% '

and last_name like ' $last _name% ' "

");

This line completes most of the work of the search. When the mysql_query function completes a query, it returns an integer flag.

The query selects all records that have the same first_name column and $first _name variable, and the Last_Name column and the $last _name variable values are also recorded in the staging recordset and the returned integer as the flag of the recordset.

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 record is found in our database. ";}

This is the final step, which is the display part. The Mysql_fetch_array function first extracts the contents of the first row of the query results and displays them in the PRINT statement. The parameter of this function is the integer flag returned by the mysql_query function. When Mysql_fetch_array executes successfully, the recordset pointer moves down automatically, so that when you execute Mysql_fetch_array again, the next line of records is what you get.

The array variable $row is created by the Mysql_fetch_array function and populated with the result field of the query, and each component of the array corresponds to each field of the query result.

If a matching record is found, the variable $row is not empty, and the statement in curly braces 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 first and then checks if the loop condition is satisfied. Since it is known that the record set is not empty, it must be executed at least once, so you should use do ... while instead of while loop. In curly braces is the loop body to be executed:

Print $row ["first_name"];

Print ("");

Print $row ["last_name"];

Print ("< p>");

Then it checks to see if the while condition is satisfied. The Mysql_fetch_array function is called again and comes to the current record's content. This process has been circulating, and when no next record exists, Mysql_fetch_array returns false, the loop ends, and the recordset is completely traversed once.

The array returned by the mysql_fetch_array ($result) can be invoked not only by field names, but also by subscripts, as in normal arrays, by referencing the various components of an array. In this way, the above code can also be written like this:

Print $row [0];

Print ("");

Print $row [1];

Print ("< p>");

We can also use the Echo function to write these four statements in a compact way:

echo $row [0], "", $row [1], "< p>";

When no matching record is found, there is no content in the $row, and the ELSE clause of the IF statement is called:

else {print "Sorry, no record is found in our database. ";}

The above describes how to send data to MySQL in PHP, including aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.