mysql&&带有id的php问题

时间:2017-02-06 19:19:21

标签: php mysql

我在终端

中收到以下错误
127.0.0.1:36368 [500]: /create_account.php - Uncaught PDOException: SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1 in /home/hue/social_network/classes/DB.php:10
Stack trace:
#0 /home/hue/social_network/classes/DB.php(10): PDOStatement->execute(Array)
#1 /home/hue/social_network/create_account.php(7): DB::query('INSERT INTO use...', Array)
#2 {main}
  thrown in /home/hue/social_network/classes/DB.php on line 10

这是我的php代码:

    <?php
    include('classes/DB.php');
    if (isset($_POST['createaccount'])) {
            $username = $_POST['username'];
            $password = $_POST['password'];
            $email = $_POST['email'];
            DB::query('INSERT INTO users VALUES (:username, :password, :email)', 
array(':username'=>$username, ':password'=>$password, ':email'=>$email));
            echo "Success!";
    }
    ?>

    <h1>Register</h1>
    <form action="create_account.php" method="post">
    <input type="text" name="username" value="" placeholder="Username ..."><p />
    <input type="password" name="password" value="" placeholder="Password ..."><p />
    <input type="email" name="email" value="" placeholder="someone@somesite.com"><p />
    <input type="submit" name="createaccount" value="Create Account">
    </form>

db class:

<?php
class DB {
        private static function connect() {
                $pdo = new PDO('mysql:host=127.0.0.1;dbname=social_network;charset=utf8', 'root', 'helloworld');
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $pdo;
        }
        public static function query($query, $params = array()) {
                $statement = self::connect()->prepare($query);
                $statement->execute($params);
                // $data = $statement->fetchAll();
                // return $data;
        }
}

我试图插入id的值:&#34;:id&#34;和&#34; \&#39; \&#39;&#34;但没有任何改变。我的id字段是auto_increment

1 个答案:

答案 0 :(得分:4)

除非您要插入所有列,否则您需要指定您正在使用的列:

INSERT INTO users (username, password, email) VALUES (:username, :password, :email)

您省略了列规范,因此默认值可能包括id和其他一些内容。

在您开始编写自己的ORM之前,请记住,有几个功能完整,经过实战测试并记录在案:DoctrinePropel和{{3}只是几个例子。