Home > Backend Development > PHP Tutorial > MySQL connection and basic operation code in php_PHP tutorial

MySQL connection and basic operation code in php_PHP tutorial

WBOY
Release: 2016-07-13 10:31:40
Original
720 people have browsed it

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

?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/761296.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...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template