Mysqli_query返回false而Mysqli_error返回NULL?

时间:2015-03-07 18:10:06

标签: php mysql mysqli insert

我一直在创建预订系统,并创建约会,但我的SQL语句不起作用。我一直试图找到解决办法,但无济于事。

下面列出的是我的PHP代码。我的第一个SQL语句完美地工作并返回正确的ClientID,但是,第二个SQL语句不会将它全部插入到数据库中。我在结果上做了var_dump,在结果上返回bool(false)和mysqli_error,返回null。 最后的错误消息只显示回显消息,而不是mysqli_error或错误号。

(注意:更改/删除某些值以保护数据)

<?php
    session_start();
    if(! $_SESSION['Username']) {
        header("location:Index.php");
    }    
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "";
    $tablename = "appointmentinformation";
    $tablenamed = "clientinformation";

    $connection = mysqli_connect("$servername", "$username", "$password", "$dbname") or die("Could not connect to the database");

    $clientusername = $_SESSION['Username'];
    $sql = "SELECT ClientID FROM $tablenamed WHERE Username = '$clientusername' LIMIT 1";
    $results = mysqli_query($connection, $sql);
    if (! $results) {
        echo ("Could not select the data : " . mysql_error());
    } else {
        $datarows = mysqli_fetch_row($results);
        $clientid = $datarows[0];
    }

    $date = $_POST["Date"];
    $month = $_POST["Month"];
    $year = $_POST["Year"];
    $time = $_POST["Time"];
    $length = $_POST["Length"];

    $date = stripslashes($date);
    $month = stripslashes($month);
    $year = stripslashes($year);
    $time = stripslashes($time);
    $length = stripslashes($length);

    $date = mysqli_real_escape_string($date);
    $month = mysqli_real_escape_string($month);
    $year = mysqli_real_escape_string($year);
    $time = mysqli_real_escape_string($time);
    $length = mysqli_real_escape_string($length);

    $query = "INSERT INTO appointmentinformation (ClientID, Length, Date, Month, Year, Time, Price) VALUES ('$clientid', '$length', '$date', '$month', '$year', '$time', '$price')";
    $result = mysqli_query($connection, $query);
    if ($result) {
        header("Location:UserCP.php");
    } else {
        echo ("Could not insert data : " . mysqli_error($result) . " " . mysqli_errno());
    }
?>

1 个答案:

答案 0 :(得分:5)

$query = "INSERT INTO appointmentinformation (ClientID, Length, Date, Month, Year, Time, Price) VALUES ('$clientid', '$length', '$date', '$month', '$year', '$time', '$price')";
    $result = mysqli_query($connection, $query);
    if ($result) {
        header("Location:UserCP.php");
    } else {
        echo ("Could not insert data : " . mysqli_error($result) . " " . mysqli_errno());
    }

mysqli_query返回的结果为null。这会将您发送到代码的else分支。然后你编写了mysqli_error($ result),它等于mysqli_error(null)。

我读过的文档说明了一个带有查询“链接”的变量。你这样做了:

 $connection = mysqli_connect("$servername", "$username", "$password", "$dbname") or die("Could not connect to the database");

您现在想将其编码为mysqli_error($ connection)和mysqli_errno($ connection)。

另外一个建议。在mysqli_connect语句之后添加此代码。

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }