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 );
?>