首页 >php教程 >php手册 >php操作mysql数据库的基本类

php操作mysql数据库的基本类

WBOY
WBOY原创
2016-05-25 16:38:11995浏览

偶尔要用到php做一些mysql数据库的操作测试,自己写起来太麻烦,搜索的结果一般都又包含一大堆没用的代码,这里将php mysql的操作做一下总结,希望以后用到的时候不用再感到麻烦了,代码如下:

<?php
$dbhost = &#39;localhost&#39;;
$dbuser = &#39;root&#39;;
$dbpass = &#39;123456&#39;;
$dbname = &#39;products&#39;;
$connect = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$connect) exit(&#39;数据库连接失败!&#39;);
mysql_select_db($dbname, $connect);
mysql_query(&#39;set names utf8&#39;);
//查询
$sql = "SELECT * FROM `category`";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
    echo $row[&#39;id&#39;];
}
//插入
$sql = "INSERT INTO `category` (`id`,`name`) VALUES (NULL,&#39;" . $name . "&#39;)";
$result = mysql_query($sql);
if (mysql_affected_rows()) {
    echo &#39;插入成功,插入ID为:&#39;, mysql_insert_id();
} else {
    echo &#39;插入失败:&#39;, mysql_error();
}
//修改
$sql = "UPDATE `category` SET `name`=&#39;" . $name . "&#39; WHERE `id`=&#39;" . $id . "&#39;"; //开源代码phprm.com
$result = mysql_query($sql);
if (mysql_affected_rows()) {
    echo &#39;修改成功!&#39;;
}
//删除
$sql = "DELETE FROM `category` WHERE `id`=&#39;" . $id . "&#39;";
$result = mysql_query($sql);
if (mysql_affected_rows()) {
    echo &#39;删除成功!&#39;;
}
//关闭连接
mysql_close($connect);


永久链接:

转载随意!带上文章地址吧。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn