写了一个连接数据库的通用类,SQL语句执行有有关问题

WBOY
Release: 2016-06-13 13:31:40
Original
982 people have browsed it

写了一个连接数据库的通用类,SQL语句执行有问题
有两个文件SqlTool.php和connector-test.php,SqlTool的代码如下:
class SqlTool
{
private $conn;
private $host="localhost";
private $user="root";
private $password="root";
private $db="db1";

function SqlTool()
{
$this->conn=mysql_connect($this->host,$this->user,$this->password);
if(!$this->conn)
{
echo("未连接数据库");
}
mysql_select_db($db,$this->conn);
mysql_query("set names utf8");
}
function execute_dml($sql)
{
$b=mysql_query($sql,$this->conn);
if(!$b)
{
return 0;
}
else 
{
if(mysql_affected_rows($this->conn)>0)
{
return 1;
}
else 
{
return 2;
}
}

}
}
?>
connector-test的代码如下:
require_once "SqlTool.php";

$sql="insert into table1 values(5,'187388','op')";
$st=new SqlTool();
$res=$st->execute_dml($sql);
if($res==0)
{
echo "执行未成功";
}
else if($res==1)
{
echo "执行成功";
}
else if($res==2)
{
echo "没有行数影响";
}
?>
现运行connector-test.php,总是显示执行未成功,不知道什么原因。望高手赐教。系统为Fedora15。

------解决方案--------------------
sql指令有错!

既然要封装数据库操作,就要把各种情况都考虑到
主要是封装错误处理
------解决方案--------------------

PHP code

#SqlTool.php
……
$b=mysql_query($sql,$this->conn);
#加一句:
if(!$b)
     die("SQL-->>: {$sql} <br>Error-->>: " . mysql_error() );  //如果出错将sql语句和mysql错误全部打出来
……
<br><font color="#e78608">------解决方案--------------------</font><br>可能执行过一次成功插入<br><br>后来的插入因为5是主键值,失败,要打印出错误如#2。加油……封装了再写框架 <div class="clear">
                 
              
              
        
            </div>
Copy after login
Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!