我想學習在php中使用mysql。我開始嘗試在mysql中創建一個表,並使用mysqli擴展。錯誤在PHP中執行sql查詢
我的代碼:
<?php
$truemsg = "Table created successfully";
$falsemsg = "Error creating table: ";
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$db = "mytable";
// Create database
$sql = "USE ".$db.";".
'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
);';
print "Sql command is ".$sql;
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
print "<p></p>";
if ($conn->query($sql) === TRUE) {
echo $truemsg;
} else {
echo $falsemsg . $conn->error;
}
$conn->close();
?>
的錯誤是:
Sql command is USE mytable;CREATE TABLE IF NOT EXISTS Authentication (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, userid VARCHAR(30) NOT NULL, password VARCHAR(30) NOT NULL, role VARCHAR(20) NOT NULL, email VARCHAR(50));
Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE TABLE IF NOT EXISTS Authentication (id INT(6) UNSIGNED AUTO_INCREMENT PR' at line 1
我嘗試了mysql命令行上粘貼相同的命令,並能正常工作。在php中使用這個問題有什麼問題?
多個查詢使用mysqli_multi_query http://php.net/manual/ro/mysqli.multi-query.php或刪除USE數據庫,並只是把數據庫連接 – Mihai