简体   繁体   中英

creating table in php mysql with quotation

I am trying to run a php mysql query through

 mysql_query("CREATE TABLE `user` (`id` NOT NULL INT,`username`  VARCHAR(30),`password`  VARCHAR(30))");

it gives me 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 'NOT NULL INT,`username`  VARCHAR(30),`password`  VARCHAR(30))'

I am new to php mysql how I can fix this syntax?

It should be:

mysql_query("CREATE TABLE `user` (`id` INT NOT NULL ,`username`  VARCHAR(30),`password`  VARCHAR(30))");

not:

mysql_query("CREATE TABLE `user` (`id` NOT NULL INT,`username`  VARCHAR(30),`password`  VARCHAR(30))");

By the way, don't use mysql_ functions they are deprecated, and in future versions of php they will get removed. Use mysqli_ instead, using them is almost the same.

From the doc :

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    [(create_definition,...)]
    ...

create_definition:
    col_name column_definition
    ...

column_definition:
    data_type [NOT NULL | NULL]
      [DEFAULT default_value]
      [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
      ...

data_type:
    BIT[(length)]
    ...
  | INT[(length)] [UNSIGNED] [ZEROFILL]

In other words, INT (or any datatype definition ) should always precede NOT NULL (or NULL ) modifier . In fact, that's true for any modifiers - DEFAULT , AUTO_INCREMENT , UNIQUE and so on.


As a sidenote, even though you're making first steps in PHP-MySQL, I'd recommend you start learning either mysqli or PDO extensions - these are a bit more sophisticated than mysql , but it's worth it.

Getting into mysql extension in 2014 will be a waste of time - it's deprecated for quite a long time already. Here's what's said on its intro page:

This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future.

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