我要马上解决这个问题。我的代码中有一行好像有问题。它和else一起返回,似乎不想运行它。它没有错误,但不会将其移动到数据库中。正如标题所说,它是if语句中的mysqli_查询。这是代码,我已经把箭头指向错误的地方。

        $t_name = $_POST['topic_name'];
        $content = $_POST['con'];
        $date = date("y-m-d");

        if(isset($_POST['submit'])) {
            if($t_name && $content) {
                if(strlen($t_name) >= 10 && strlen($t_name) <= 70) {
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
                    if($query = mysqli_query($connect, "INSERT INTO topics('topic_id', 'topic_name', 'topic_content', 'topic_creator', 'date') VALUES ('', '".$t_name."', '".$content."', '".$_SESSION["username"]."', '".$date."')")) {
                        echo "<font color = 'green'>Topic posted!</font>";
                    } else {
                        echo "<font color='red'>Unknown failure, time to panic!</font>";
                    }
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                } else {
                    echo "<font color='red'>Topic name must be between 10 and 70 characters long!</font>";
                }
            } else {
                echo "<font color='red'>All fields must be filled out!</font>";
            }
        }
    } else {
        include('header.php');
        echo "You must be logged in to access this page.  Click <a href='login.php'>here</a> to login.";
    }
    include('footer.php');

是的,我知道SQL注入和其他事情的危险性,一旦我的代码写下来,我就会处理它。

最佳答案

您的topic_id不能设置为空。相反,删除topic_id或给它一个default值。
另外,像前面提到的@HizerCache一样,可以使用MySQL函数NOW()插入当前时间。
像这样的:

"INSERT INTO topics(topic_id, topic_name, topic_content, topic_creator, date) VALUES (default, '".$t_name."', '".$content."', '".$_SESSION["username"]."', NOW())"

另外,使用mysqli_error()调试错误。
if($query = mysqli_query($connect, "INSERT INTO topics('topic_id', 'topic_name', 'topic_content', 'topic_creator', 'date') VALUES ('', '".$t_name."', '".$content."', '".$_SESSION["username"]."', '".$date."')")) {
    echo "<font color = 'green'>Topic posted!</font>";
} else {
    echo "Error : " . mysqli_error($connect);
}

关于php - mysqli_query在If语句中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36819760/

10-10 14:51