Home  >  Article  >  Backend Development  >  MySQL connection and basic operation code in PHP (quick test use, simple and convenient)_PHP tutorial

MySQL connection and basic operation code in PHP (quick test use, simple and convenient)_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:31:47671browse

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.

Copy code The code is as follows:

$dbhost='localhost';//Database server Name
$dbuser='root';//Username to connect to the database
$dbpass='123456';//Password to connect to the database
$dbname='products';//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);
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/761019.htmlTechArticleOccasionally I need to use PHP to do some mysql database operation tests. It is too troublesome to write it myself. The search results are generally It also contains a lot of useless code. Here is the operation of php mysql...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn