简体   繁体   中英

mysqli and php creating a table that doesn't exist

What's wrong with my code ?

It returns the following error:

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 'EXIST test1 ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(3' at line 1

<?php
$servername = "localhost";
$username = "root";
$password = "passtest";
$database = "daily";
$table = "test1";


$conn = new mysqli($servername, $username, $password, $database);


if (mysqli_connect_error()) {
    die("Database connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";



$sql = "CREATE TABLE IF NOT EXIST $table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL
)";

if ($conn->query($sql) === TRUE) {
    echo "Table MyGuests created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}

$conn->close();
?> 

Your SQL instruction should be:

$sql = "CREATE TABLE IF NOT EXISTS $table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL
)";

--> NOT EXIST S

<?php
$con = mysqli_connect("localhost","root","passtest","daily");
if (mysqli_connect_error()) {
die("Database connection failed: " . 
mysqli_connect_error());
}

$create_table = "CREATE TABLE IF NOT EXIST `test1` 
(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL
)";

$create_tbl = $con->query($create_table);
if ($create_table)
{
    echo "Table has created";
}
else 
{
    echo "error!!";  
}

$con->close();
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM