Write a generic class that connects to the database, and SQL statement execution has a problem

Source: Internet
Author: User
wrote a generic class to connect to the database, the SQL statement was executed with a problem
There are two files in sqltool.php and Connector-test.php,sqltool code as follows:
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 ("Database Not Connected");
}
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;
}
}

}
}
?>
The code for Connector-test is as follows:
Require_once "sqltool.php";

$sql = "INSERT INTO table1 values (5, ' 187388 ', ' op ')";
$st =new SqlTool ();
$res = $st->execute_dml ($sql);
if ($res ==0)
{
echo "Execution unsuccessful";
}
else if ($res ==1)
{
echo "Successful execution";
}
else if ($res ==2)
{
echo "No row count effect";
}
?>
Now running connector-test.php, always shows that execution is unsuccessful and does not know what the reason is. Hope Master Enlighten. The system is FEDORA15.

------Solution--------------------
SQL command is wrong!

Since you want to encapsulate database operations, you need to take all the circumstances into account
Mostly encapsulation error handling
------Solution--------------------
PHP Code
#SqlTool. php ... $b =mysql_query ($sql, $this->conn); #加一句: if (! $b)     
Error-->>: ". Mysql_error ()); If an error occurs, all the SQL statements and MySQL errors are called out ...
------Solution--------------------
A successful insert may have been performed

Later inserts because 5 is the primary key value, failed, to print out an error such as # #. Come on...... Encapsulates the re-write frame
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.