Home > Article > Backend Development > MySQL connection and basic operation code in PHP (quick test use, simple and convenient)_PHP tutorial
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 to use it in the future. No more hassle when you arrive.
//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);
?>