用于INSERT、UPDATE、DELETE和Search的Php-Mysqli简单类方法



我的CRUD类中有以下代码

//function to execute prepared statement query
//$sql = select , insert, update and or delete query => insert into table(col,col,col,...col) values(?,?,?,...?);
//$dataTypes = "ssidb", it could be any char in s=>string, i=>integer, d=>double and b=>blob data
//$param = $val1,$val2,$val3,....$valn, this is an option coma separated values to bind with query
public function dbQuery($sql,$dataTypes="",$param=""){
    try{
        $this->connect();
        $stmt = $this->con->stmt_init();
        $stmt = $this->con->prepare($sql);
        $stmt->bind_param($dataTypes, $param);          
        if($stmt->execute() === true){
            return true;    
            }
        else{
            return false;   
            }
        }catch(Exception $e){
            $this->errorMsg = $e->getMessage(); 
        }
        $this->closeConnection();
    }

我在我的索引页面上调用这个方法,如下所示:

 if(isset($_POST['btnSearch'])){
 //search for some record with primary key
 $sno = intval($_POST['sno']);
 $sql = "SELECT sno,std_name,email,roll_number FROM table_1 WHERE sno = ?";
 $dTypes = "i";
 $params = $sno;
if($db->dbQuery($sql,$dTypes,$params)){
    echo('Record exists');
    }
else{
    echo('Record did not found'.$db->errorMsg);
    }
}//search for record

//将值插入表1表

这总是返回true,是否存在任何记录?这个代码出了什么问题?

您的代码中存在许多缺陷,即使修复了这个特定的问题,它也永远无法按预期工作。

在开始一个类之前,您需要大量练习原始API函数,并学习如何用心使用它们。否则,你的课堂将只是一个稻草屋,它会从最柔软的触摸中崩溃。

现在来谈谈你的问题。

要解决它,您需要理解一个非常重要的数学概念,即"空结果不是错误"。10-5-5=0并不意味着你的计算有错误!这仅仅意味着结果为零。

这里完全一样。当数据库没有返回行时,并不意味着存在错误。它只是表示没有数据可返回。

反之亦然:如果没有错误,并不意味着找到了行。

要查看是否返回了任何行,您需要获取该行

因此,不必检查execute()结果,只需将行提取到一个变量中,然后检查它是否包含任何内容。

最新更新