This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 5 years ago.
Do you have any idea whats wrong with my code? I can't really figure it out.
Connection failed: 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 'VARCHAR(50) NOT NULL, url TEXT(65535) NOT NULL, ip VARCHAR(150) NOT NULL)' at line 3
<?php
$host = "localhost";
$dbname = "nope";
$username = "nope";
$password = "nope";
if(isset($_GET["s"])){
try{
$pdo = new PDO("mysql:host=".$host.";dbname=".$dbname,$username,$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$table = "links";
$sql ="CREATE TABLE IF NOT EXISTS $table(
ID INT(11) AUTO_INCREMENT PRIMARY KEY,
key VARCHAR(50) NOT NULL,
url TEXT(65535) NOT NULL,
ip VARCHAR(150) NOT NULL)";
$pdo->exec($sql);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
/*$statement = $pdo->prepare("select url from $table where key = :key");
$statement->execute(array(':key' => $_GET["s"]));
$result = $statement->fetch();
echo $result;*/
}
else{
echo "error";
}
?>
Your column name key is a reserved keyword in mysql
The solution is to quote the column name in backticks
`key` VARCHAR(50) NOT NULL,
or just change the name of the column to whatever you like which is not a reserved word.
my_key VARCHAR(50) NOT NULL,
So your statement should be
$sql ="CREATE TABLE IF NOT EXISTS $table(
ID INT(11) AUTO_INCREMENT PRIMARY KEY,
`key` VARCHAR(50) NOT NULL,
url TEXT(65535) NOT NULL,
ip VARCHAR(150) NOT NULL)";
or
$sql ="CREATE TABLE IF NOT EXISTS $table(
ID INT(11) AUTO_INCREMENT PRIMARY KEY,
table_key VARCHAR(50) NOT NULL,
url TEXT(65535) NOT NULL,
ip VARCHAR(150) NOT NULL)";
Try the following query instead:
CREATE TABLE IF NOT EXISTS $table(
`ID` INT(11) AUTO_INCREMENT PRIMARY KEY,
`key` VARCHAR(50) NOT NULL,
`url` TEXT NOT NULL,
`ip` VARCHAR(150) NOT NULL)
Key is a Reserved Word in MariaDB. And thus needs to be enclosed in ``. And there is no need to define length for type TEXT
Related
I want to create a table with variables passed into my php file. However, the SQL does not work when I pass in '12345' and works when I pass in 'a12345' instead.
This is my error that is given.
Error creating the table
query was
CREATE TABLE 123456 ( humidity VARCHAR(50) NOT NULL, temperature VARCHAR(50)
NOT NULL, gasquality VARCHAR(50) NOT NULL, timestamp DATETIME NOT NULL
DEFAULT CURRENT_TIMESTAMP)
mysqlerror: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
'123456 ( humidity VARCHAR(50) NOT NULL, temperature VARCHAR(50) NOT NULL,
gasq' at line 1
Creating database failed!
and my function that creates the table
function CreateTableNode(&$formvars)
{
$serialno = $formvars['serialno'];
$qry = "CREATE TABLE ".$serialno." (".
" humidity VARCHAR(50) NOT NULL, ".
" temperature VARCHAR(50) NOT NULL, ".
" gasquality VARCHAR(50) NOT NULL, ".
" timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)";
if(!mysqli_query($this->connection,$qry))
{
$this->HandleDBError("Error creating the table \nquery was\n $qry");
return false;
}
return true;
}
I want to be able to create tables with numeric names like '12345' or '154124' for other purposes. Thanks alot!
My suggestion:
Provide a prefix to the table you created.
Moreover, I couldn't
see the primary key in your table. However, it is not necessary to
have it but if your table design doesn't have a primary key, you need
to rethink your design. It plays a vital role to join tables.
Your code can be rewritten as:
function CreateTableNode (&$formvars) {
$host = 'localhost';
$database = 'test';
$dbuser = 'root';
$dbpass = '';
try {
$pdo = new PDO('mysql:host=localhost; dbname=test', $dbuser, $dbpass);
} catch (PDOException $e) {
print "ERROR! : " . $e->getMessage() . "<br/>";
die();
}
$serialno = $formvars['serialno'];
$qry = "CREATE TABLE ".$serialno." ("."
`id` INT NOT NULL AUTO_INCREMENT ,
`humidity` VARCHAR(50) NOT NULL ,
`temperature` VARCHAR(50) NOT NULL ,
`gasquality` VARCHAR(50) NOT NULL ,
`timestamp` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`)
)";
$stmt = $pdo->prepare($qry);
$stmt->execute();
$pdo = null;
return true;
}
You just need to wrap some elements in the query with quotes as the duplicated thread mentioned by underscore_d says:
$qry = "CREATE TABLE '$serialno' (
'humidity' VARCHAR(50) NOT NULL,
'temperature' VARCHAR(50) NOT NULL,
'gasquality' VARCHAR(50) NOT NULL,
'timestamp' DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)";
This will fix your syntax errror in the query.
Marking to close the question as duplicated
The name of the entity was expected. (near "123456" at position 13)
Try adding a prefix to the table name as such
"t_12345"
CREATE TABLE t_12345
MySql does not allow numeric values as table name.
MySQL doesn't allow the creation of tables with names made solely of digits unless the name is quotes. See here
Identifiers may begin with a digit but unless quoted may not consist solely of digits.
Try quoting the name with backticks (`) or prefix the table name.
The error says "Creating database failed!".
So I assume you haven't selected the database in the connection query. You should do that or select it with "use mydatabase;" first. Of course, you may need to create the database first.
With PDO it would look like:
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
Please see dbname=myDB which preselects the right db for you.
Reference: https://www.w3schools.com/php/php_mysql_connect.asp
Using mysql functions, you can use:
mysql_select_db($dbname)
Reference: http://php.net/manual/en/function.mysql-select-db.php
I am following a codeiniter tutorial, which tells me to make a database with the following code (using mysql):
$sql = "create database login;
CREATE TABLE IF NOT EXISTS `user_login` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) NOT NULL,
`user_email` varchar(255) NOT NULL,
`user_password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ";
I try to run this, using my own php code, but i keep getting this error, and have no idea how to solve it:
Error creating table: 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 'CREATE TABLE IF NOT EXISTS `user_login` ( `id` int(11) NOT NULL AUTO_INCREM' at line 2
No idea what it could be.
create database login;
and
CREATE TABLE IF NOT EXISTS `user_login` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) NOT NULL,
`user_email` varchar(255) NOT NULL,
`user_password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
are two commands which are to be executed separately. Have the database created before you try to create the table - either via a SQL client or by executing something like:
$sql1 = 'create database login;';
$sql1->execute();
$sql2 = 'CREATE TABLE IF NOT EXISTS `user_login`...';
$sql2->execute();
can anyone please assist me, that whats wrong i m doing. There is no syntax error in the php code, but output is- connection successful
Table customers NOT created. Error: 1064
Table stats NOT created. Error : 1005. I am using XAMPP, with PHP 7
<?php
$conn = mysqli_connect("localhost","root","","test");
if(mysqli_connect_errno()){
echo "Connect failed%\n".mysqli_connect_errno();
exit();
}
else {
echo "connection successful";
}
$sql1 = "CREATE TABLE CUSTOMERS (
P_Id int(10) NOT NULL AUTO_INCREMENT,
Firstname(100) varchar NOT NULL,
Lastname(100) varchar NOT NULL,
Address varchar(500) NOT NULL,
City varchar(100) NOT NULL,
PRIMARY KEY(P_Id)
)";
if(mysqli_query($conn,$sql1)==1){
echo "Table customers created successfully";
}
else
{
echo "<br/>"."Table customers NOT created. Error: ".mysqli_errno($conn);
}
$sql2 = 'CREATE TABLE STATS (
O_Id int(10) NOT NULL AUTO_INCREMENT,
Offers varchar(1000) NOT NULL,
Resorts varchar(1000) NOT NULL,
ArrivalDate date NOT NULL,
P_Id int(10) NOT NULL,
PRIMARY KEY(O_Id),
FOREIGN KEY(P_Id) REFERENCES CUSTOMERS(P_Id)
)';
if(mysqli_query($conn,$sql2)==1){
echo "Table stats created successfully";
}
else
{
echo "<br/>"."Table stats NOT created. Error : ".mysqli_errno($conn);
}
?>
You need to specify the character limit for VARCHAR after the VARCHARkeyword. So, for example, in the query for table CUSTOMERS, the Firstname clause will look like:
Firstname VARCHAR(100) NOT NULL
The error is how you declare your varchar.
Firstname(100) varchar NOT NULL,
Must be :
Firstname varchar(100) NOT NULL,
So change firstname and lastname syntax and all will work right.
Hope this help.
I think your problem is column declarations:
You should use: <name> <type>(length) NOT NULL
I have below code I am trying to run..Connection is successfully created but still mysqli_query does not create a table.What I am missing...
here is the script I am executing...
error_reporting(E_ALL);
ini_set('display_errors', '1');
$con=mysqli_connect("localhost","xxxxxx","xxxxx","xxx");
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
} else {
echo "Successful database connection";
}
$tbl_users = "CREATE TABLE IF NOT EXISTS users (
id INT(11) NOT NULL AUTO_INCREMENT,
firstname VARCHAR(255) NOT NULL,
lastname VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
gender ENUM('m','f') NULL,
state VARCHAR(255) NULL,
country VARCHAR(255) NULL,
userlevel ENUM('admin','user') NOT NULL DEFAULT 'user',
ip VARCHAR(255) NOT NULL,
signup DATETIME NOT NULL,
lastlogin DATETIME NOT NULL,
activated ENUM('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (email)
)";
$query = mysqli_query($con, $tbl_users);
if ($query === TRUE) {
echo "<h3>user table created OK :) </h3>";
} else {
echo "<h3>user table NOT created :( </h3>";
}
You need to change your Primary key to the auto_increment column, remove it from email, you can set this (email) to unique if it should be
CREATE TABLE IF NOT EXISTS users (
id INT(11) NOT NULL // >>> PRIMARY KEY //<<< AUTO_INCREMENT,
firstname VARCHAR(255) NOT NULL,
[Err] 1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
PRIMARY KEY (email) is the issue. Make id your primary key.
I'm trying to create multiple tables with a query, but it doesn't seem to work. I'm using PHP code to execute the query. Below is my PHP code, my query and my error.
My PHP code:
<?php
$conn=mysql_connect("localhost","secret","secret") or die("Kan geen verbinding maken met de DB server");
mysql_select_db("secret",$conn) or die("Kan database niet selecteren");
$query_file = 'tables.txt';
$fp = fopen($query_file, 'r');
$sql = fread($fp, filesize($query_file));
fclose($fp);
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
mysql_close($conn);
?>
My query:
CREATE TABLE pages(
id INT NOT NULL AUTO_INCREMENT,
pagid VARCHAR(32) NOT NULL,
title VARCHAR(32) NOT NULL,
content TEXT NOT NULL,
image VARCHAR(65) NOT NULL,
youtube VARCHAR(32) NOT NULL,
primary key ( id ));
CREATE TABLE members(
id INT NOT NULL AUTO_INCREMENT,
username VARCHAR(65) NOT NULL,
password VARCHAR(65) NOT NULL,
primary key ( id ));
CREATE TABLE news(
id INT NOT NULL AUTO_INCREMENT,
pagid VARCHAR(32) NOT NULL,
title VARCHAR(32) NOT NULL,
content TEXT NOT NULL,
image VARCHAR(150) NOT NULL,
youtube VARCHAR(32) NOT NULL,
date VARCHAR(32) NOT NULL,
primary key ( id ));
CREATE TABLE gallery(
id INT NOT NULL AUTO_INCREMENT,
image VARCHAR(65) NOT NULL,
title VARCHAR(65) NOT NULL,
description TEXT NOT NULL,
url VARCHAR(200) NOT NULL,
category VARCHAR(65) NOT NULL,
primary key ( id ));
My 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 'CREATE TABLE members( id INT NOT NULL AUTO_INCREMENT, username VARCHA' at line 10
Does anyone have any idea what I'm doing wrong here?
Try this:
$q1 = "CREATE TABLE pages(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
pagid VARCHAR(32) NOT NULL,
title VARCHAR(32) NOT NULL,
content TEXT NOT NULL,
image VARCHAR(65) NOT NULL,
youtube VARCHAR(32) NOT NULL)";
$q2 = "CREATE TABLE members(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(65) NOT NULL,
password VARCHAR(65) NOT NULL)";
mysql_query($q1);
mysql_query($q2);
If you're using mysql_query, it only supports one query at a time.
However, I would recommend you avoid using mysql_* functionality as its depreciated. Try mysqli or PDO
You're propably using mysql_query. The documentation explicitly states that multiple queries are not supported. As each of your create statements is an own query, you'll have to split up your query string.