Basic PHP and MySQL tutorial (i)

Source: Internet
Author: User
Tags mysql tutorial php and mysql php3 file
HTML and PHP, MySQL interaction

Why use a database?
World Wide Web (WWW) is more than just a place to provide information. If you have something, make a Web site, you can share it with people all over the world. However, this is not an easy thing to do. When the site gets bigger, you may encounter problems such as:

The site contains so many things that visitors can't get what they want quickly. This problem is, to a certain extent, fatal to a website.
Visitors want to provide information to you, and this information must be saved for later use.
The above two problems can be solved by the database!

In the world of WWW, databases are everywhere. Big as Yahoo!, Amazon, EBay, small to a simple message board, you can see where the database comes in. It can even be said that the database is the basis for all advanced applications.

Why use PHP and MYSQL
As I know, almost all of the major commercial web site databases are SQL-based. One of the most popular may be Oracle. It's very powerful, and of course, it's expensive. SQL is not an application, but a language that is shorthand for structured query Language (Structured Query language) to manipulate and query the database.

In recent years, some companies have developed "open-code" SQL applications, the most famous of which may be MySQL. It's not just for free, it's not much less than Oracle for a typical small to medium database application.

To run MySQL on a Web site, you need a scripting language to interact with the database. In the past, Perl was the most popular. But now it looks like PHP is a little bit better. Don't ask me what the difference is between them?? In the past I used Perl and it worked very well, but now it seems like everyone likes to use PHP. Its popularity certainly has its truth.

The software you need
This part of the content, Chinabyte Network College earlier in the article has been introduced. Readers can refer to the article "setting up local PHP development for Win98". This is no longer detailed here.

HTML and PHP
Author: Yang Eyebrow compiling this article click: 398

Let's take a look at how PHP works. Take a look at the following code:

< html>

< body>

< PHP

PRint "Hello, world.";

?>

</body>


When this page is requested, it will display "Hello, World" in the browser.

As you can see, the PHP script is embedded in the HTML file. It takes "<? "Start with"?> "end. Not only that, we can even embed HTML tags in PHP scripts:

< PHP

Print "< html>";

Print "< body>";

Print "Hello, world.";

Print "</body>";

Print "
?>

The two methods are the same, the effect is the same. But in some special cases, it is more convenient to choose one of them.
PHP's Prints statement
Author: Yang Eyebrow compiling this article click: 398

The simplest interaction between PHP and HTML is done through the print statement:

< PHP

Print "Hello, world.";

?>

Print is the simplest and most used function to display some text in a browser window, and the Echo function is similar to print, but you can use the "," number to separate multiple items for display, which is handy when mixing string constants and variable displays.

There is also a printf function, which is used to format the output of a number. You can use a number as an integer, or display it in scientific notation.

In these functions, the use of parentheses is different:

Echo must not have parentheses
printf must have
Print optional
To display a string or a number is simple, simply follow the variable name or constant behind the print statement. However, if you want to display an array, is it also written like this:

Print $myarray;

The result of the output will be "array", which PHP tells you $myarray is an array. This is useful when you are unsure whether a variable is an array, but what we want to see now is the contents of the array.

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 delimiter for the contents of the array. When the conversion is complete, the contents of the array are linked by delimiters to form a string:

$implodedarray = Implode ($myarray, ",");

Print $implodedarray;

You can also use the Array_walk function to implement the display of an array. This function performs the same function operation on each of the contents of the array. For example:

function Printelement ($element)

{

Print ("$element < p>");

}

Array_walk ($myarray, "printelement");
How PHP sends data to MySQL
Author: Yang Eyebrow compiling this article click: 398

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 ["Fir
How PHP extracts data from MySQL
Author: Yang Eyebrow compiling this article click: 398

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. ";}
Check if the query is working correctly
Author: Yang Eyebrow compiling this article click: 398

Do your SELECT, DELETE, or other queries work correctly? This must be clear, and do not easily jump to conclusions.

Checking an INSERT query is relatively simple:

$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 method of checking does not work for SELECT queries, and should be done as follows:

$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 succeeded. ";

}

ElseIf (mysql_num_rows ($selectresult) = = 0)

{

Print "Select query failed. ";

Exit

}

For the DELETE query, this should be the case:

$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

}

The above is the PHP and MySQL Basic Tutorial (a) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.