代码之家  ›  专栏  ›  技术社区  ›  Steve Mack

Mysqli绑定参数不工作

  •  0
  • Steve Mack  · 技术社区  · 7 年前

    我试图使用准备好的语句将数据输入数据库。没有准备好的陈述有效,但这个准备好的陈述无效。我不知道为什么。 准备版本:

    $stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path) 
    VALUES (?, ?, ?, ?)");
    $stmt->bind_param('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
    $stmt->execute();
    

    未准备的版本:

      $sql = "INSERT INTO videos (file_name, upload_by, date, path) VALUES ('$newstring', '$id', '
              $date', 'Nominator/$location$newstring')";
      mysqli_query($mysqli, $sql);
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   Amit Gupta    7 年前

    代替 $stmt-execute(); 具有 $stmt->execute();

    另外,不要使用 date path 在查询中。用其他名称重命名它们,如 date1 path1 .

    按以下方式更新您的查询,这肯定会起作用(离线测试):

    <?php
    $mysqli = new mysqli('localhost', 'root', '', 'test2'); 
    
    if ($mysqli->errno) {
    printf("Connect failed: %s\n", $mysqli->error);
    exit();
    }
    
    $stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date1, path1) VALUES (?, ?, ?, ?)");
    $stmt->bind_param('ssss', $file_name, $upload_by, $date1, $path1);
    $date1 = date("Y-m-d");
    $file_name = "test.jpg";
    $upload_by = "amit";
    $path1 = "test";
    if ($result = $stmt->execute()){
    echo "success";
    $stmt->free_result();
    } else {
    echo "error";
    }
    $stmt->close();
    ?>
    
        2
  •  -1
  •   Ibrahim Abdulrahman    7 年前

    如果只使用?,则绑定参数两次?,不再绑定参数,直接执行即可。

     //Prepare your query first
     $stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path) 
        VALUES (?, ?, ?, ?)");
    
    //Just pass your argument and execute directly without binding the parameter (The parameter is binded already)
    $stmt->execute('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
    
    推荐文章
    Z Davies  ·  绑定参数错误
    9 年前