Use of MySQL in PHP

Source: Internet
Author: User
Use MySQL in PHP to connect to MySQL:

Mysql_connect ():

$ Dbc = mysql_connect ($ host, $ user, $ password );

Select the current database:

Mysql_select_db ($ database_name );

Mysql_select_db ('$ database_name', $ conn );

Eg:

  
 

  

If the function cannot return a valid resource link, or die () and die () are executed to terminate the script execution.

Execute a simple query:

$result=mysql_query($query);

  

For simple queries such as insert, update, and delete, they do not return records, and the $ result variable returns true or false, depending on whether the query is successful. For complex queries (select, show, describe, and explain) that return records, if the query is valid, the $ result variable is a resource link pointing to the query result. if the query is invalid, the $ result variable is false.

 1  2 
 \n";64   }65   echo 'Please try again!';66   }67 ?>68 

  

  

Close the existing MySQL link:

Mysql_close (); // php will automatically close the connection at the end of the script, so this is not required.

Search query results

Format:

mysql_fetch_row(result);


Note: mysql_fetch_row is used to save a row of query results to an array. the subscript of this array starts from 0, and each array element corresponds

One domain. You can obtain all query results through a loop.

Format:

1 mysql_fetch_array(result);

  

Note: The functions of mysql_fetch_array and mysql_fetch_row are basically the same, except that they can be offset from 0.

You can also use a domain name as an index.

Returns all the domain values of the next row and saves them to an array. If no row exists, false is returned.

mysql_query("set name 'GBK'")  

  

// Use GBK Chinese encoding

The main tool for processing select query results is mysql_fetch_array (), which carries a query result variable ($ result) and returns a row of data in array format at a time.

Read each record from the query:

  while($row=mysql_fetch_array($result))               {                     .........               }

  

The mysql_fetch_array () function also has an option to specify the type of returned array: Union array, index array, or both. Union arrays allow column values to be referenced by names, while index arrays require only numbers, as shown in the following table:

Constant

Example

MYSQL_ASSOC

$ Row ['column ']

MYSQL_NUM

$ Row [0] (faster)

MYSQL_BOTH

$ Row [0] or $ row ['column '] (default)

Release query information:

   mysql_free_result($result);

  

This step is not required because PHP will automatically release resources at the end of the script.

Eg:

 1 
  8    NAMEid'; 9  10    while($row=mysql_fetch_array($result,MYSQL_ASSOC))11    {12    echo ''.$row['name'].''.$row['id'].'';13    }14    echo '';15    mysql_free_result($result);16   }17  18   else19   {20   echo '

The current users could not be retrieved.We apologize for any inconvenience

';21 echo mysql_error();22 }23 mysql_close();24 25 ?>

  

The running result is:

Tips

The mysql_fetch_array () function is equivalent to the mysql_fetch ($ result, MYSQL_NUM) function.

The mysql_fetch_assoc () function is equivalent to the mysql_fetch_array ($ result, MYSQL_ASSOC) function.

You must use mysql_query () to perform a query, and then use mysql_fetch_array () to retrieve the information of a single row. to retrieve multiple rows, you can use a while loop (instead of a for or foreach loop ).


Ensure SQL security

PHP database security can be summarized into two categories:

1. protect database access information

2. be careful when running the query.

Use specific

mysql_real_escape_string()

Function, escape the characters that may have problems to clear the data:

$ Data = mysql_real_escape_string ($ data, $ dbc );

This function is the same as addslashes. It is more specific to databases.

Use the ini_get () function to test the Magic Quotes status. This function returns the configuration in the PHP configuration file for a specific option. If the ini_get () function returns true, it indicates that Magic Quotes is enabled ?? All slashes will be removed before mysql_real_escape_string () is applied.

In the current pHP version, Magic Quotes is disabled by default. Therefore, ini_get () returns FALSE without removing any existing slashes.

If Magic Quotes is enabled, it will automatically add "\" before the characters to be escaped, and this will often cause errors when we write data to the database, therefore, use stripslashes ($ string) to remove those. Then call the mysql_real_escape_string () function.

Eg:

1    function escape_data($data)2               {3          global $dbc;4          if(ini_get('magic_quotes_gpc'))5           {6         $data=stripslashes($data);7            }8   retrun mysql_real_escape_string(trim($data),$dbc);9   }

  

Tips

The language used by mysql_real_escape_String () function is used to escape strings.

The mysql_real_escape_string () function requires a database connection.

The get_magic_quotes_gpc () function can also be used to return the current Magic Quotes setting.

Ini_get () can be used to get many different php. ini settings, not just the settings of Magic Quotes.

Statistics returned Records

Mysql_num_rows (), returns the number of rows of the select query index, and takes the query result as a parameter.

Eg:

$ Num = mysql_num_rows ($ result );

Other common Mysql functions

mysql_insert_id

Returns the ID of the last INSERT command.


mysql_tablename

Get database name

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.