Mysql connection and basic operation code in php (quick test and use, simple and convenient) _ php instance

Source: Internet
Author: User
Tags php mysql
This article mainly introduces the mysql connection and basic operation code in php, which is used for quick testing. it is simple and convenient. it is required for beginners of PHP, you can refer to the occasional use of php to perform some mysql database operation tests. it is too troublesome to write yourself. The search results generally contain a lot of useless code, here we will summarize the operations of php mysql, and hope that it will not be used in the future.

The code is as follows:


$ Dbhost = 'localhost'; // database server name
$ Dbuser = 'root'; // User name used to connect to the database
$ Dbpass = '000000'; // password used to connect to the database
$ Dbname = 'products'; // database name

// Connect to the database
$ Connect = mysql_connect ($ dbhost, $ dbuser, $ dbpass );
If (! $ Connect) exit ('database connection failed! ');
Mysql_select_db ($ dbname, $ connect );
Mysql_query ('set names utf8'); // sets the encoding

// Query operation
$ SQL = "SELECT * FROM 'Category '";
$ Result = mysql_query ($ SQL );
While ($ row = mysql_fetch_array ($ result )){
Echo $ row ['id'];
}
// Insert operation
$ SQL = "INSERT INTO 'category '('id', 'name') VALUES (NULL,'". $ name ."')";
$ Result = mysql_query ($ SQL );
If (mysql_affected_rows ()){
Echo 'Insert successful, insert ID: ', mysql_insert_id ();
} Else {
Echo 'insertion failed: ', mysql_error ();
}
// Modify the operation
$ SQL = "UPDATE 'category' SET 'name' = '". $ name. "'where' ID' ='". $ id ."'";
$ Result = mysql_query ($ SQL );
If (mysql_affected_rows ()){
Echo 'modification successful! ';
}
// Delete operation
$ SQL = "DELETE FROM 'category' WHERE 'id' = '". $ id ."'";
$ Result = mysql_query ($ SQL );
If (mysql_affected_rows ()){
Echo 'deleted! ';
}
// Close the connection
Mysql_close ($ connect );
?>

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.