我将所有sql存储在另一个文件中调用db_function.php 这是代码
<?php
class DB_Functions
{
private $conn;
function __construct()
{
require_once'conn.php';
$conn = mysqli_connect("localhost","root","","phpstmt");
}
function __desturct()
{
}
public function add($tablename,$colname,$dataname)
{
$sql = "INSERT INTO ".$tablename." (".$colname.") VALUES (".$dataname.")";
$result= mysqli_query(mysqli_connect("localhost","root","","phpstmt"), $sql);
return $result;
}
}
?>
这里是index.php中的我的代码,其中是接口
if(isset($_POST['btnsubmit'])) {
$dataphp = $_POST["data"];
$datatwophp = $_POST["datatwo"];
$colname = "data,datatwo";
$dataname = "'$dataphp','$datatwophp'";
$result = $db->add($tablename,$colname,$dataname);
//$sql = "INSERT INTO `table` (`data`,`datatwo`) VALUES ('$dataphp','$datatwophp')";
if($result) {
echo "success";
} else {
echo "WrongE: " . $result . "<br>" . mysqli_error($conn);
}
}
我甚至不知道错误是什么,因为错误输出只是一个WrongE,$结果就像消失一样。
欣赏并回答。
答案 0 :(得分:0)
排队
echo "WrongE: " . $result . "<br>" . mysqli_error($conn);
您无法访问DB_Functions
属性$conn
。如果您愿意,可以在DB_Functions
类
public function getConn()
{
return $this->conn;
}
然后你必须从构造函数
替换这一行$conn = mysqli_connect("localhost","root","","phpstmt");
用这个
$this->conn = mysqli_connect("localhost","root","","phpstmt");
然后你需要替换这行代码
echo "WrongE: " . $result . "<br>" . mysqli_error($conn);
用这个
echo "WrongE: " . $result . "<br>" . mysqli_error($db->getConn());
或者如果你想要,你可以在DB_Functions
类中添加一个特殊方法来获取错误
public function getError()
{
return mysqli_error($this->conn);
}
然后就可以像这样使用这种方法
echo "WrongE: " . $result . "<br>" . $db->getError();
$result
并未消失 - 当您尝试将其作为字符串回显时,不会显示false
值。如果你试试这个代码
$test = false;
$string = ':' . $test . ':';
echo $string;
然后你会看到输出上的::
字符串。
你的最后一堂课看起来像这样
<?php
class DB_Functions
{
private $conn;
function __construct()
{
require_once'conn.php';
$this->conn = mysqli_connect("localhost","root","","phpstmt");
}
function __desturct()
{
}
public function add($tablename,$colname,$dataname)
{
$sql = "INSERT INTO ".$tablename." (".$colname.") VALUES (".$dataname.")";
$result= mysqli_query(mysqli_connect("localhost","root","","phpstmt"), $sql);
return $result;
}
public function getError()
{
return mysqli_error($this->conn);
}
}
?>
然后你的index.php看起来像这样
if(isset($_POST['btnsubmit'])) {
$dataphp = $_POST["data"];
$datatwophp = $_POST["datatwo"];
$colname = "data,datatwo";
$dataname = "'$dataphp','$datatwophp'";
$result = $db->add($tablename,$colname,$dataname);
//$sql = "INSERT INTO `table` (`data`,`datatwo`) VALUES ('$dataphp','$datatwophp')";
if($result) {
echo "success";
} else {
echo "WrongE: " . $result . "<br>" . $db->getError();
}
}