Occasionally I need to use PHP to do some operation tests of MySQL database. It is too troublesome to write it myself. The search results usually contain a lot of useless code. Here is a summary of the operation of PHP MySQL. I hope you won’t have to worry about it when you use it in the future.
The code is as follows:
$dbhost='localhost';//Database server name
$dbuser='root';//Connect database username
$dbpass='123456';//Password to connect to the database
$dbname='products';//The name of the database
//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');//Set 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 'Insertion successful, insertion ID is:',mysql_insert_id();
}else{
echo 'Insertion failed:',mysql_error();
}
//Modification 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 'Delete successfully! ';
}
//Close the connection
mysql_close($connect);
?>