PHP and MySQL Basic Tutorial (1)

xiaoxiao2021-03-05  26

HTML and PHP, MySQL interaction

Why use the database?

World Wide Web (WWW) is more than just a place to provide information. If you have anything, make a website, you can also share with people around the world. However, this is not a very easy thing. When the website is more, you may encounter such problems:

The website contains too many things, making visitors can't get what they want very quickly. This issue is fatal for a website to some extent.

Visitors want to provide you with information, and this information must be saved for later use.

The above two questions can be solved by the database!

In the world of WWW, the database is everywhere. As Yahoo! Amazon, eBay, small to a simple message board, you can see the use of the database. It can even be said that the database is the foundation of all advanced applications.

Why do I know with PHP and MySQL, almost all major commercial website databases are based on SQL. The most popular may have Oracle. It is very powerful, of course, it is also expensive. SQL is not an application, but a language, it is a short written for Structure Query Language, which is used to operate and query the database.

In the last few years, some companies have developed SQL applications of "Open Code", where the most famous may be Mysql. It is not just free, for a general small and medium database application, its performance is not inferior to Oracle.

To run mysql on a website, you need a scripting language to interact with the database. In the past, Perl is the most popular. But now it seems that PHP seems to be more excellent. Don't ask me what is there? ? In the past, I used Perl, it works very well, but now everyone likes to use PHP. Its popularity has its truth.

Let's take a look at how PHP works. Take a look at this code below:

Print "Hello, World."

? >

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

It can be seen that the PHP script is embedded in the HTML file. It ends with "". Not only that, we can even embed the HTML tag in the PHP script:

Print "";

Print "";

Print "Hello, World."

Print "";

Print "";

? >

The two methods are the same, the effect is the same. But in some special cases, one of them is more convenient.

PHP's Prints statement

The simplest interaction of PHP and HTML is implemented by a Print statement:

Print "Hello, World.";? >

Print is the most simpler function that is also used, used to display some text in the browser window, the echo function is similar, but you can use "," to separate multiple points, this is mixing It is convenient when string constants and variables are displayed.

There is also a Printf function that formats the output of the figures. You can use a number as an integer or displayed with a scientific count.

In these functions, the use of parentheses is different:

Echo must not bring parentheses Printf but must have prints that can be available without displaying a string or a number is simple, just follow the variable name or constant followed behind the print statement. However, if you want to display an array, is it written like this:

Print $ myarray;

The result of its output will be "array", PHP tells you $ myArray is an array. This will have some use when you don't have a variable is an array, but now we want to see 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, the second is the separator of the array content. When the conversion is completed, the content of the array is linked by the separator to form a string:

$ impLodedArray = Implode ($ MyArray, ",");

Print $ IMPLODEDArray;

You can also use the Array_Walk function to implement the display of the array. This function performs the same function to perform the same function to each content of the array. E.g:

Function Printelement ($ ELEMENT)

{

Print ("$ Element

");

}

Array_walk ($ MyArray, "Printelement");

How does PHP send data to MySQL

You should have a better understanding of the HTML form. The following code is a very simple HTML form:

Last name:

Name:

When you enter the data, then press the Submit button, this form will send the data to SubmitForm.php3. Then by this PHP script process the received data, the following is the code: SubmitForm.php3:

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 ("

");

Print ("Thank Fill in Registry");

? >

"Username" and "Password" in the third line of the code represent the account and password you log in to the MySQL database, respectively. "DBNAME" in the fifth line represents the name of the mysql database. "TableName" in the thirteenth row is the name of a data table in the database.

When you press Submit, you can see the name you entered is displayed in a new page. Look at the URL column of the browser, it should be like this:

... /SUBMITFORM.PHP3? First_name = FRED & LAST_NAME = FLINTSTONE

Because we use the form get method, the data is transmitted to SubmitForm.php3 through the URL. Obviously, the GET method is limited. When you want to pass, you can't use GET, you can only use the POST method. But no matter what method, when the data transfer is completed, PHP automatically creates a variable as the fields in each form (the Name property of the form) in each form.

All PHP variables have started with one dollar symbol, so that in the process of submitform.php3 script processing, there will be two variables of first_name and $ last_name, and the content of the variable is what you entered.

Let's check if the name you entered is really entered into the database. Start MySQL, enter your mysql> prompt:

mysql> Select * from Tablename;

You should get a table, the content is what you just entered:

| first_name | Last_name |

| Liu |

1 ROWS IN SET (0.00 sec)

Let's analyze how submitform.php3 work:

The beginning of the script is:

MySQL_Connect (localhost, username, password);

MySQL_SELECT_DB (DBNAME);

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

The following line is to perform a SQL statement: mysql_query ("INSERT INTO TABLENAME (First_name, Last_name)

VALUES ('$ first_name', '$ last_name')

");

The mysql_query function is used to perform a SQL query on the selected database. You can execute any SQL statements in the MySQL_Query function. The executed SQL statement must be enclosed as a string with a double quotes, where the variables are enclosed in single quotes.

There is a thing to pay attention to: MySQL's statement to end with a semicolon (;), a line PHP code is also the same, but the mysql statement in the PHP script does not have a semicolon. That is, 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 this command appears in the PHP script, you have to remove the semicolon. The reason why this is because some statements, such as SELECT and INSERT, have no semicolons to work. But there are still some statements, such as Update, plus the semicolons can't. In order to avoid trouble, remember this rule is fine.

How does PHP extracts data from MySQL

Now we build another HTML form to perform this task:

Please enter your query:

Last name:

Name:

Similarly, there must be a PHP script to handle this form, we build a SearchForm.php3 file:

MySQL_Connect (localhost, username, password);

MySQL_SELECT_DB (DBNAME);

IF ($ first_name == "")

{$ first_name = '%';}

IF ($ last_name == "")

{$ last_name = '%';}

$ result = mysql_query ("SELECT * from TableNamewhere First_name Like '$ First_Name%'

And last_name limited '$ last_name%'

");

IF ($ row = mysql_fetch_array ($ result)) {

Do {

Print $ ROW ["first_name"];

PRINT ("");

Print $ ROW ["Last_name"];

Print ("

");

} while ($ row = mysql_fetch_array ($ result));

} Else {Print "Sorry, in our database, no records are found.";

? >

When you enter the content you want to retrieve in your form, then press the Submit button, you will enter a new page, where all matching search results are listed. Let's take a look at how this script is in the search task.

The previous statements are the same as those mentioned above, first establish a database connection, then select the database and data table, which is necessary for each database application. Then there is such a few statements:

IF ($ first_name == "")

{$ first_name = '%';}

IF ($ last_name == "")

{$ last_name = '%';}

These lines are used to check if the fields of the form are empty. It should be noted that the two equal numbers, because PHP's syntax is mostly from the C language, the usage of this is the same as C: one equal sign is assignment number, two equal numbers represent logic. It should also be noted that when the condition is true, the statement to be executed later is placed in "{" and "}", and each statement is followed by the semicolon indicate statement.

The 100%% is a wildcard of the SQL language. After understanding one, it will know the meaning of the two lines: If the "first_name" field is empty, then all of the first_name will be listed. The two sentences will also mean the same .

$ results = mysql_query ("SELECT * from TableName

Where first_name like '$ first_name%'

And last_name limited '$ last_name%' "

");

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

The query selects the same number of first_name columns and $ first_name variables from all records, and the Last_Name column and the $ Last_name variable value are also the same record, put it in the temporary record set, and use the returned integer as the logo of this recordset.

IF ($ row = mysql_fetch_array) {DO {

Print $ ROW ["first_name"];

PRINT ("");

Print $ ROW ["Last_name"];

Print ("

");

} while ($ row = mysql_fetch_array ($ result));

} Else {Print "Sorry, in our database, no records are found.";

This is the final step, that is, the display is part. The mysql_fetch_array function first extracts the contents of the first line of the query result, and display it with the print statement. The parameter of this function is an integer flag returned by the mysql_query function. After mysql_fetch_array executed, the record set pointer will automatically move so that when executing mysql_fetch_array once again, the next bank record is the content.

Array Variable $ ROW is created by the mysql_fetch_array function and uses the query result field to populate each component of the array corresponding to each field of the query result.

If there is a recorded record, the variable $ ROW will not be empty, and the statement in the curly brackets is performed:

Do {

Print $ ROW ["first_name"];

PRINT ("");

Print $ ROW ["Last_name"];

Print ("

");

} while ($ row = mysql_fetch_array ($ result));

This is a Do ... while loop. Unlike the While loop, it is performed first, and then checks if the cycle condition is satisfied. Since it is already known that the record set is not empty, it must be performed at least once, so it should be used by do ... while instead of the While loop. The cyclic body to be performed in the curly bracket:

Print $ ROW ["How to extract data from MySQL

Now we build another HTML form to perform this task:

Please enter your query:

Last name:

Name:

Similarly, there must be a PHP script to handle this form, we build a searchform.php3 file:

MySQL_Connect (localhost, username, password);

MySQL_SELECT_DB (DBNAME);

IF ($ first_name == "")

{$ first_name = '%';}

IF ($ last_name == "")

{$ last_name = '%';}

$ results = mysql_query ("SELECT * from TableName

Where first_name like '$ first_name%'

And last_name limited '$ last_name%'

");

IF ($ row = mysql_fetch_array ($ result)) {

Do {

Print $ ROW ["first_name"];

PRINT ("");

Print $ ROW ["Last_name"];

Print ("

");

} while ($ row = mysql_fetch_array ($ result));

} Else {Print "Sorry, in our database, no records are found.";

? >

When you enter the content you want to retrieve in your form, then press the Submit button, you will enter a new page, where all matching search results are listed. Let's take a look at how this script is in the search task.

The previous statements are the same as those mentioned above, first establish a database connection, then select the database and data table, which is necessary for each database application. Then there is such a few statements:

IF ($ first_name == "")

{$ first_name = '%';}

IF ($ last_name == "")

{$ last_name = '%';}

These lines are used to check if the fields of the form are empty. It should be noted that the two equal numbers, because PHP's syntax is mostly from the C language, the usage of this is the same as C: one equal sign is assignment number, two equal numbers represent logic. It should also be noted that when the condition is true, the statement to be executed later is placed in "{" and "}", and each statement is followed by the semicolon indicate statement.

The 100%% is a wildcard of the SQL language. After understanding one, it will know the meaning of the two lines: If the "first_name" field is empty, then all of the first_name will be listed. The two sentences will also mean the same . $ results = mysql_query ("SELECT * from TableName

Where first_name like '$ first_name%'

And last_name limited '$ last_name%' "

");

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

The query selects the same number of first_name columns and $ first_name variables from all records, and the Last_Name column and the $ Last_name variable value are also the same record, put it in the temporary record set, and use the returned integer as the logo of this recordset.

IF ($ row = mysql_fetch_array ($ result)) {

Do {

Print $ ROW ["first_name"];

PRINT ("");

Print $ ROW ["Last_name"];

Print ("

");

} while ($ row = mysql_fetch_array ($ result));

} Else {Print "Sorry, in our database, no records are found.";

This is the final step, that is, the display is part. The mysql_fetch_array function first extracts the contents of the first line of the query result, and display it with the print statement. The parameter of this function is an integer flag returned by the mysql_query function. After mysql_fetch_array executed, the record set pointer will automatically move so that when executing mysql_fetch_array once again, the next bank record is the content.

Array Variable $ ROW is created by the mysql_fetch_array function and uses the query result field to populate each component of the array corresponding to each field of the query result.

If there is a recorded record, the variable $ ROW will not be empty, and the statement in the curly brackets is performed:

Do {

Print $ ROW ["first_name"];

PRINT ("");

Print $ ROW ["Last_name"];

Print ("

");

} while ($ row = mysql_fetch_array ($ result));

This is a Do ... while loop. Unlike the While loop, it is performed first, and then checks if the cycle condition is satisfied. Since it is already known that the record set is not empty, it must be performed at least once, so it should be used by do ... while instead of the While loop. The cyclic body to be performed in the curly bracket:

Print $ ROW ["first_name"]; print ("");

Print $ ROW ["Last_name"];

Print ("

");

Then check if the WHILE condition is satisfied. MySQL_FETCH_ARRAY function is called again to get the content of the current record. This process has been looping. When there is no next record, mysql_fetch_array returns false, the loop is over, and the record set is completely traversed once.

The array returned by mysql_fetch_array ($ result) not only can be called by field name, but also use the subscript to reference the components of the array as a general array. In this way, the above code can be written as this:

Print $ ROW [0];

PRINT ("");

Print $ ROW [1];

Print ("

");

We can also use the ECHO function to write the compact of these four statements:

Echo $ ROW [0], "", $ ROW [1], "

";

When there is no matching record, there will be no content in $ row, and the Else clause of the IF statement will be called:

Else {Print "Sorry, in our database, no records are found.";

Check if the query is working properly

Is your SELECT, DELETE or other queries work properly? This is a need to be clear, and don't easily conclusions.

Check if an insert query is relatively simple:

$ results = mysql_query ("INSERT INTO TABLENAME (first_name, last_name)

VALUES ('$ first_name', '$ last_name')

");

IF (! $ results)

{

Echo " INSERT query failed: ", mysql_error ();

EXIT;

}

However, this check method is inseparable for SELECT queries, at this time, it should be:

$ 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 is successful."

}

Elseif ($ SELECTRESULT) == 0)

{

Print "SELECT query failed."

EXIT;

}

And for the Delete query, it 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 success";

}

Elseif (MySQL_AFFECTED_ROWS ($ deleteResult)! = 1)

{

Print "delete query failed";

EXIT;

}

转载请注明原文地址:https://www.9cbs.com/read-34964.html

New Post(0)