php和mysqli代码不会将数据输入我的数据库

时间:2015-05-22 14:47:45

标签: php mysqli

数据库名称:forumTutorial
表名:threads

4 Columns:  
id      - INT     - 5    Length - Primary Key - Auto Increment (AI/A_I).  
title   - VARCHAR - 255  Length
content - VARCHAR - 2000 Length  
author  - VARCHAR - 255  Length

我没有得到任何错误..它只是说未能创建

<?php
session_start();
//$_SESSION['username'] = 'Admin';
$con = mysqli_connect('localhost', 'root', '', 'forumTutorial') or die(mysql_error());
if (isSet($_POST['createThread'])) {
    if (isSet($_POST['title']) && $_POST['title'] != '' && isSet($_POST['content']) && $_POST['content'] != '' && isSet($_SESSION['username']) && $_SESSION['username'] != '') {
        $title = $_POST['title'];
        $content = $_POST['content'];
        $user = $_SESSION['username'];
        $q = mysqli_query($con, "INSERT INTO `threads` VALUES ('', '$title', '$content', '$user')");
        if ($q) {
            echo 'Thread created.';
        }else
            echo 'Failed to create thread.';
    }
}?>
<html>
<head></head>
<body>
    <h1>Create Thread:</h1>
    <form action='forumTutorial.php' method='POST'>
    <table>
        <tbody>
            <tr>
                <td>Title: </td><td><input type='text' name='title' /></td>
            </tr>
            <tr>
                <td>Description: </td><td><input type='text' name='content' /></td>
            </tr>
            <tr>
                <td></td><td><input type='submit' value='Create Thread' name='createThread' /></td>
            </tr>
        </tbody>
    </table>
    </form>
</body>

1 个答案:

答案 0 :(得分:0)

您需要在插入查询中指定字段。此外,由于您的id字段设置为AUTO_INCREMENT,因此您不应发送任何值。改变这个:

$q = mysqli_query($con, "INSERT INTO `threads` VALUES ('', '$title', '$content', '$user')");

对此:

$q = mysqli_query($con, "INSERT INTO `threads` (title, content, author) VALUES ('$title', '$content', '$user')");