2016-06-10 87 views
-1

我試圖運行此代碼:mysqli的INSERT INTO查詢不能

<?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,它的回聲「只有創建的表!」但它應該是回聲'BOTH表&數據創建!',有人可以幫我解決它嗎?

編輯:

其他人,將有同樣的問題,即什麼解決它:(感謝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)"; 
+2

開始使用__quotes__ –

+1

爲了擴大對@ u_mulder的評論,字符串SQL值必須被引用。 –

+0

@u_mulder謝謝!這對我行得通。 –

回答

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(); 

?> 
+0

我試過這個,NULL值作爲字符串而不是NULL值,所以用於僅字符串值的引號... –

+0

是根據數據類型使用plz,它被廣義化 – User2403