Home>

We are working on a certain issue.
We are proceeding while investigating the linkage between PHP and MySQL.
I think we can connect, but the table creation doesn't work.
The database has been created.
I get a grammar error, but I don't understand it at all.
What's wrong?

php version is 5.2.4 (depending on specification)
Server information is hidden.

<? php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Connect to MySQL database
try {
$db = new PDO ("mysql: dbname = $dbname;host = $servername;charset = utf8mb4", $username, $password,
              [
            PDO :: ATTR_ERRMODE =>PDO :: ERRMODE_EXCEPTION,
            PDO :: ATTR_DEFAULT_FETCH_MODE =>PDO :: FETCH_ASSOC,
        ]);
    print ('Connection succeeded');
// Table creation contents
$sql = "CREATE TABLE keijiban (
num INT (10) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR,
comment VARCHAR,
date DATETIME,
password INT
) engine = innodb default charset = utf8 ";
// Execute table creation
$prepare = $db->prepare ($sql);
    $prepare->execute ();
    $result = $prepare->fetchAll ();
    var_dump ($result);
} catch (PDOException $e) {
    print ("Connection error:". $e->getmessage ());
die ();
}
?>


Error description

The connection was successful. Connection error: SQLSTATE [42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;check the manual that corresponds to your MariaDB server version for the right syntax to use near '' num 'INT (10) AUTO_INCREMENT PRIMARY KEY, 'name' VARCHAR, 'comment' VARCHAR, 'da' at line 2

  • Answer # 1

    Run it directly into the DB and use it from the program after success.
    You can use PHPMyAdmin or the command line.
    SQL that is executed directly and does not succeed naturally does not succeed no matter where it is executed.

    As with PHP, "Syntax error" is a syntax error.

    Check the documentation if you get a syntax error.

    MySQL 5.6 Reference Manual/.../Creating a table

    I think the problem is probably that the VARCHAR type does not have a specified number of digits.
    Decide how many digits you want because it is a specification.

    Snacks:
    I think there are almost no cases of CREATE TABLE directly from PHP.
    I try to create it every time I run PHP, but there's no such program (if it doesn't contain IF NOT EXISTS, it's an error)
    That's fine for practice, but only if it's not practical.