mysqli插入查询无法正常工作

时间:2016-06-10 10:16:48

标签: php mysqli

我尝试运行此代码:

<?php

define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'mydb');

$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
$query = "SHOW TABLES LIKE 'users'";
$result = $mysqli->query($query);

if ($result->num_rows == 0) {
    $query = "CREATE TABLE users (id INT UNSIGNED NOT NULL AUTO_INCREMENT, username VARCHAR(50) NOT NULL, password VARCHAR(100) NULL, name VARCHAR(50) NULL, phone VARCHAR(50) NULL, active BOOLEAN NOT NULL, PRIMARY KEY (id), UNIQUE (username)) ENGINE = MyISAM";

    if ($mysqli->query($query)) {
        $query = "INSERT INTO users (id, username, password, name, phone, active) VALUES (1, admin, 321, idan, 123456789, 1), (2, guest, NULL, NULL, NULL, 1)";

        if ($mysqli->query($query)) {
            echo 'BOTH table & data created!';
        }
        else {
            echo 'ONLY table created!';
        }
    }
    else {
        echo 'NOTHING created!';
    }
}
else {
    echo 'users table are exists!';
}

$result->free();
$mysqli->close();

?>

虽然用户表不是exiest,但它是echo'仅创建表'!但它应该是回声“BOTH table&amp;数据创建!',有人可以帮我解决吗?

编辑:

对于会遇到同样问题的其他人,可以解决问题:(感谢u_mulder)

$query = "INSERT INTO users (id, username, password, name, phone, active) VALUES (1, 'admin', '321', 'idan', '123456789', 1), (2, 'guest', NULL, NULL, NULL, 1)";

1 个答案:

答案 0 :(得分:0)

Use quotes in your values, try this, it works fine

<?php

define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'mydb');

$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
$query = "SHOW TABLES LIKE 'users'";
$result = $mysqli->query($query);

if ($result->num_rows == 0) {
    $query = "CREATE TABLE users (id INT UNSIGNED NOT NULL AUTO_INCREMENT, username VARCHAR(50) NOT NULL, password VARCHAR(100) NULL, name VARCHAR(50) NULL, phone VARCHAR(50) NULL, active BOOLEAN NOT NULL, PRIMARY KEY (id), UNIQUE (username)) ENGINE = MyISAM";

    if ($mysqli->query($query)) {
        $query = "INSERT INTO users (id, username, password, name, phone, active) VALUES ('1', 'admin', '321', 'idan', '123456789', '1'), ('2', 'guest', 'NULL', 'NULL', 'NULL', '1')";

        if ($mysqli->query($query)) {
            echo 'BOTH table & data created!';
        }
        else {
            echo 'ONLY table created!';
        }
    }
    else {
        echo 'NOTHING created!';
    }
}
else {
    echo 'users table are exists!';
}

$result->free();
$mysqli->close();

?>