php - 准备好的查询无法运行 PHP

标签 php mysql mysqli

我正在尝试使用准备好的查询,但此代码不起作用,它只是停留在第一次使用准备()时。注释第一个 if() 没有任何作用,现在它停留在第二个上。没有连接问题/没有错误,只是卡住了。

如果我只使用 mysqli_query() 完成所有这些工作,一切都会很好。

function addUser($id){
/*
  if ($stmt = $this->mysqli->prepare("SELECT * FROM Users WHERE ID = ?")){

    if (!($stmt->bind_param("s", $id))){
      return false;
    }

    if ($stmt->execute()) {
      if ($stmt->num_rows!=0){
        return false;
      }

    }else{
      return false;
    }

  }else{
    return false;
  }*/

  if ($stmt = $this->mysqli->prepare("INSERT INTO Users VALUES (?, '')")) {

    if (!$stmt->bind_param("s", $id)) {
      return false;
    }

    if (!$stmt->execute()) {
      return false;
    }

    return true;
  }

  return false;

}

关于调试,如果我像这样更改代码

function addUser($id){
  echo "1";
  if ($stmt = $this->mysqli->prepare("SELECT * FROM Users WHERE ID = ?")){
    echo "2";
    if (!($stmt->bind_param("s", $id))){
      return false;
    } ...

  }else{
    echo "3";
  } ...

我在页面上只会看到“1”。

类(class)开始:

class db{
    private $mysqli;

    function __construct($ip, $login, $password, $database){
      $this->mysqli = new mysqli($ip, $login, $password, $database) or die("Problem with DB connection!"); 
      $this->mysqli->set_charset("utf8");
    }

最佳答案

你永远不会execute(),所以什么也不会发生,因此不会引发错误。

这是我的写法:

function addUser($id){
    if ($this->mysqli->connect_errno) {
        die('Connect Error: ' . $this->mysqli->connect_errno);
    }
    if ($stmt = $this->mysqli->prepare("INSERT INTO Users VALUES (?, '')")) {
        $stmt->bind_param("s", $id);//did you mean i  for type int ?
        $stmt->execute();//dont forget this!!
    }else{
        die('Connect Error: ' . $this->mysqli->connect_errno);
    }

    return ($stmt->rowCount() > 0)? true : false;

}

关于php - 准备好的查询无法运行 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26068260/

相关文章:

php - 数字字符串(任意大小)-> 多个整数

php - mysqli_fetch_array在已部署的服务器上不起作用

php - 从数据库中删除特定行以及相应按钮上的 html 表单击

php - 如何在 Phalcon 中创建新的可注入(inject)服务

php - 使用 "Foreach"循环在 php 中生成一个 javascript 数组

php - 仅当下拉值为 'other' 时才验证 'other' 字段

c# - 如果在调用 commit 或 rollback 之前断电会怎样?

mysql - BASH 脚本不读取输入的 mysql 密码

php - mysqli 子查询字符串不起作用

php - mysql_connect 不能在远程服务器而不是本地服务器上工作