预备语句:列不能为空

时间:2018-09-12 17:38:02

标签: php mysql

我一直试图找出为什么在准备好的语句中出现此错误,但我无法解决问题。我收到错误消息:

Notice: Undefined index: tipimage in C:\xampp\htdocs\Matt\addtip.php on line 68
ERROR: Could not execute query: INSERT INTO tips (tiptitle, tiptext, tiplink, tipimage) VALUES (?, ?, ?, ?). Column 'tipimage' cannot be null

数据库中的所有值均设置为文本类型,但ID除外。

....
else {
        /* Attempt MySQL server connection. Assuming you are running MySQL
        server with default setting (user 'root' with no password) */
        $mysqli = new mysqli("localhost", "paul", "pass", "yourcomp");

        // Check connection
        if($mysqli === false){
            die("ERROR: Could not connect. " . $mysqli->connect_error);
        }

        // Prepare an insert statement
        $sql = "INSERT INTO tips (tiptitle, tiptext, tiplink, tipimage) VALUES (?, ?, ?, ?)";

        if($stmt = $mysqli->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("ssss", $tiptitle, $tiptext, $tiplink, $tipimage);

            // Set parameters
            $tiptitle = $_REQUEST['tiptitle'];
            $tiptext = $_REQUEST['tiptext'];
            $tiplink = $_REQUEST['tiplink'];
            $tipimage = $_REQUEST['tipimage'];

            // Attempt to execute the prepared statement
            if($stmt->execute()){
                $successmsg = "<div class='alert alert-success'>Tip Added Successfully!</div>";
            } else{
                echo "ERROR: Could not execute query: $sql. " . $mysqli->error;
            }
        } else{
            echo "ERROR: Could not prepare query: $sql. " . $mysqli->error;
        }

1 个答案:

答案 0 :(得分:2)

您正在寻找未随请求发送的POST变量。 undefined index通知正试图告诉您。在将其传递到数据库之前,您无需检查它是否存在,因此最终将其传递为null。只需提供一个空字符串的默认值(此处使用null coalesce operator),它将正常工作。

$tipimage = $_REQUEST['tipimage'] ?? "";