偶尔要用到php做一些mysql数据库的操作测试,自己写起来太麻烦,搜索的结果一般都又包含一大堆没用的代码,这里将php mysql的操作做一下总结,希望以后用到的时候不用再感到麻烦了,代码如下:
<?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = '123456'; $dbname = 'products'; $connect = mysql_connect($dbhost, $dbuser, $dbpass); if (!$connect) exit('数据库连接失败!'); mysql_select_db($dbname, $connect); mysql_query('set names utf8'); //查询 $sql = "SELECT * FROM `category`"; $result = mysql_query($sql); while ($row = mysql_fetch_array($result)) { echo $row['id']; } //插入 $sql = "INSERT INTO `category` (`id`,`name`) VALUES (NULL,'" . $name . "')"; $result = mysql_query($sql); if (mysql_affected_rows()) { echo '插入成功,插入ID为:', mysql_insert_id(); } else { echo '插入失败:', mysql_error(); } //修改 $sql = "UPDATE `category` SET `name`='" . $name . "' WHERE `id`='" . $id . "'"; //开源代码phprm.com $result = mysql_query($sql); if (mysql_affected_rows()) { echo '修改成功!'; } //删除 $sql = "DELETE FROM `category` WHERE `id`='" . $id . "'"; $result = mysql_query($sql); if (mysql_affected_rows()) { echo '删除成功!'; } //关闭连接 mysql_close($connect);
永久链接:
转载随意!带上文章地址吧。