PHP PDO INSERT停止重复条目[duplicate]

zhte4eai  于 2023-03-16  发布在  PHP
关注(0)|答案(2)|浏览(123)

此问题在此处已有答案

Inserting into a mysql table and overwritng any current data(5个答案)
昨天关门了。
我需要一些帮助,让这个代码的工作,使它能够防止重复进入数据库的cname,ccode,crgeno和cvatno。请帮助。

//My DB Code
public function insert($cname, $ccode, $cregno, $cvatno)
    {
        $sql = "INSERT INTO tbl_client (ccode, cname, cregno, cvatno) VALUES (:amcname,:amccode,:amcregno,:amcvatno)";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute(['amcname' => $cname, 'amccode' => $ccode, 'amcregno' => $cregno, 'amcvatno' => $cvatno]);
        return true;
    }

//My action Code
if(isset($_POST['action']) && $_POST['action'] == "insert"){
        $cname = $_POST['amcname'];
        $ccode = $_POST['amccode'];
        $cregno = $_POST['amcregno'];
        $cvatno = $_POST['amcvatno'];
        
        $db->insert($cname, $ccode, $cregno, $cvatno);
         
    }

@Simone:这么做的:

public function insert($cname, $ccode, $cregno, $cvatno)
    {

        $query = $this->conn->prepare("SELECT cname FROM tbl_client WHERE cname = ?");
        $query->bind_param('s',$cname);
        $query->execute();
        $result = $query->get_result();
        $count = $result->num_rows;

        if($count===0){
            $sql = "INSERT INTO tbl_client (ccode, cname, cregno, cvatno) VALUES (:amcname,:amccode,:amcregno,:amcvatno)";
            $stmt = $this->conn->prepare($sql);
            $stmt->execute(['amcname' => $cname, 'amccode' => $ccode, 'amcregno' => $cregno, 'amcvatno' => $cvatno]);
            return true;
        };   
    }

:(还是有问题...

bvhaajcl

bvhaajcl1#

请改用以下代码:

public function insert($cname, $ccode, $cregno, $cvatno) {

  $query = $this->conn->prepare("SELECT COUNT(cname) as countname FROM tbl_client WHERE cname = ?");
  $query->bind_param('s',$cname);
  $query->execute();
  $result = $query->get_result();
  $count = $result->fetch_assoc()['countname']; //count will > 0 if exist in db.
  if ($count === 0) {
    //query insert
  }

}

请记住始终准备查询。

zf9nrax1

zf9nrax12#

你的问题不是很清楚,如果你想检查记录不存在,然后插入它,你的代码必须这样做,它可能在这一部分你有问题

$count = $result->num_rows;

如果使用PDO,请使用

$count = $result->rowCount;

因此,如果您想删除旧记录并插入新记录REPLACE Statement,您也可以使用替换以更好的方式执行此操作。或者,如果记录存在INSERT ... ON DUPLICATE KEY UPDATE Statement,您可以进行更新

相关问题