PHP and MySQL basic tutorial (1) _ MySQL

Source: Internet
Author: User
Tags php3 file
Why should databases be used for interaction between HTML, PHP, and MySQL? WorldWideWeb (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 problem: The website contains too many East HTML and PHP and MySQL interactions.

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 application, but a Language. it is short for Structured Query Language (Structured Query Language), used to operate and Query databases.

In recent years, some companies have developed "open code" SQL applications, the most famous of which may be 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 has been introduced in the ChinaByte network school's previous articles. 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 "
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 the PHP script, you need to remove the,, V, V,? SELECT and INSERT. do you have a semicolon to work. 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;

}

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.