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 3 years ago.
there is some problem with my code. Everytime I try to insert something into the database, I get the syntax error.
Here is my database structure:
CREATE TABLE `notes` (
`id` int(12) NOT NULL,
`type` varchar(15) NOT NULL,
`title` varchar(43) NOT NULL,
`text` varchar(43) NOT NULL,
`group` varchar(32) NOT NULL,
`uid` int(64) NOT NULL,
`creator` int(64) NOT NULL,
`insert_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `notes`
ADD PRIMARY KEY (`id`);
ALTER TABLE `notes`
MODIFY `id` int(12) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=79;
And thats my code
<?php
session_start();
require '../config.php';
$notetype = $_POST['type'];
$notetitle = $_POST['title'];
$notetext = $_POST['text'];
$notegroup = $_POST['group'];
$noteuid = $_POST['uid'];
$notecreator = $_POST['creator'];
$notetbname = $note['tbname'];
$conn = new mysqli($databaseconfig['ip'], $databaseconfig['user'], $databaseconfig['pass'], $databaseconfig['dbname']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO $notetbname (type, title, text, group, uid, creator)
VALUES ('$notetype', '$notetitle', '$notetext', '$notegroup', $noteuid, $notecreator);";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This is what I get as error message:
Error: INSERT INTO notes (type, title, text, group, uid, creator) VALUES ('player', 'Hello there', 'Good morning everybody', 'Cop', 3325, 103);
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 'group, uid, creator) VALUES ('player', 'Hello there', 'Good morning everybody'' at line 1
This is because group is a mysql's reserved word.
change the fieldname or try this (notice the backtick " ` " before and after the word group:
$sql = "INSERT INTO $notetbname (type, title, text, `group`, uid, creator)
VALUES ('$notetype', '$notetitle', '$notetext', '$notegroup', $noteuid, $notecreator);";
Here you can find a list of all reserved word (mysql 5.5)
https://dev.mysql.com/doc/refman/5.5/en/keywords.html#keywords-5-5-detailed-G
Related
I am using the following awesome, easy & lightweight database class: https://codeshack.io/super-fast-php-mysql-database-class/
My problem is I do not know how I can figure out if a table in the database exists or not. I have the following PHP Code:
function addSts($database, $brow, $vers, $pag, $lang) {
$tablename = "sts" . $pag;
$stsinsert = $database->query('INSERT INTO ' . $tablename . '(id, browser, version, language, date) VALUES (NULL, ?, ?, ?, current_timestamp())', $brow, $vers, $lang);
if ($stsinsert->affectedRows()) {
echo "TABLE EXISTS";
$database->close();
}
else {
echo "TABLE DOES NOT EXISTS -> CREATE TABLE";
$pagecreation = $database->query('CREATE TABLE ' . $tablename . ' (`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `browser` VARCHAR(20) NOT NULL, `version` VARCHAR(10) NOT NULL, `language` VARCHAR(5) NOT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_DATE(), PRIMARY KEY (`id`))');
if ($pagecreation) {
addSts($brow, $vers, $pag, $lang);
}
}
}
It always throws the following error: Unable to prepare MySQL statement (check your syntax) - Table 'testdb.ststest' doesn't exist
So and here we have the salad. It throws the error and does not go further to the if-else part. SO every time the table does not exist the program stops working.
Hope somebody can help me out.
Thanks in advance.
If you can, use the information_schema DB and query TABLES tables
select * from tables where TABLE_SCHEMA like '<database name>'
e.g. select * from tables where TABLE_SCHEMA like 'mydbdev'
the simply iterate through the results OR
select * from tables where TABLE_SCHEMA like '<database name>' AND TABLE_NAME like '<table name>';
and count the rows (should be 0 if not present or 1 if it is).
As #Barmar mentioned in the comments, you can use try/catch statements to do this.
function addSts($database, $brow, $vers, $pag, $lang) {
$tablename = "sts" . $pag;
try {
// try to insert first
$stsinsert = $database->query('INSERT INTO ' . $tablename . '(id, browser, version, language, date) VALUES (NULL, ?, ?, ?, current_timestamp())', $brow, $vers, $lang);
if ($stsinsert->affectedRows()) {
echo "TABLE EXISTS";
$database->close();
}
}
catch (\Exception $e){
echo "TABLE DOES NOT EXISTS -> CREATE TABLE";
$pagecreation = $database->query('CREATE TABLE ' . $tablename . ' (`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `browser` VARCHAR(20) NOT NULL, `version` VARCHAR(10) NOT NULL, `language` VARCHAR(5) NOT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_DATE(), PRIMARY KEY (`id`))');
if ($pagecreation) {
// call the function to insert data
addSts($brow, $vers, $pag, $lang);
}
}
}
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 3 years ago.
I am about to create a table, but I want to declare it based on the user's input. thankyou for any response, all answers are appreciated, more power!
I am receiving this error (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 ''2020-2021' ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR' at line 1)
here's the sample code I am doing.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mias";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$table = $_POST['usersinput'];
// sql to create table
$sql = "CREATE TABLE $table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
Try this code by replacing your code. It will work. i have tried. Problem in your last line of your code.
CREATE TABLE $table(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30),
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
As Nigel has said in the comment, it's definitely a bad idea to allow user input to create a table.
How I would think about doing this would be to use relationships between the Table Guests and the Table or Booking you want them to be added to.
You would just need to create two tables, one for the Booking and one for the Guests then in the Guests table, have a Booking_ID field which would contain the ID of the bookings the user should be added to.
This way, when you want to look for Guests for a specific table, you would be able to do SELECT * FROM MyGuests WHERE booking_id=[the booking id] and this would return the guests for that table.
Like other users stated there are several reasons (most importantly security) not to do that, but if you really want it you have to use concatenation for your string:
Option
$sql = "CREATE TABLE {$table}(id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30), email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";
Option
$sql = "CREATE TABLE" . $table . "(id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30), email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";
I cannot access the textbox content to create the table in Mysql and the error is
"Error creating table: Incorrect table name ''
<?php
$conn=mysqli_connect("localhost","root","","abc");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = isset($_POST['email']) ? $_POST['email'] : '';
// sql to create table
$sql = "CREATE TABLE `$email` (
`id` INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`firstname` VARCHAR(30) NOT NULL,
`lastname` VARCHAR(30) NOT NULL,
`email` VARCHAR(50),
`regdate` TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
If error is "Error creating table: Incorrect table name" and you query has:
CREATE TABLE `$email`
Most probably $email has an # sign in it, that shouldn't be part of a table name - use only [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore).
It is not likely that a table should be created each form sublimation, and that its name should be dynamic (you will not know it to query data from this table).
Not less important - never use user input directly in your SQL (to avoid SQL injection). Reference:
PHP MySQLi Prepared Statements Tutorial to Prevent SQL Injection
You can try as follows-
$email = $_POST['email'];
// sql to create table
$sql = "CREATE TABLE IF NOT EXISTS $email(
`id` INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`firstname` VARCHAR(30) NOT NULL,
`lastname` VARCHAR(30) NOT NULL,
`email` VARCHAR(50),
`regdate` TIMESTAMP
)";
I have an html form in which a person fills an input field. The input field will then be sent to the PHP form handler. The form handler will then process it and the variable input in the html form will then become the name of an SQL table. Everything is okay except that part of making the variable the name of SQL table.
Look at my code:
<?php error_reporting(E_ALL); ini_set('display_errors', 1);?>
<?php $title =$_POST['myfile']?>
<?php $info =$_POST['info']?>
<?php $tags =$_POST['tags']?>
<?php $category =$_POST['category']?>
<?php $allowcomments =$_POST['allowcomments']?>
<?php $flagging =$_POST['flagging']?>
<?php $visibility =$_POST['visibility']?>
<?php $date =$_POST['date']?>
<?php $name =$_POST['name']?>
<?php $size =$_POST['size']?>
<?php $type =$_POST['type']?>
<?php $path =$_POST['path']?>
<?php $sub =$_POST['sub']?>
<?php $cap =$_POST['cap']?>
<?php
$servername='localhost';
$username='root';
$password='you aint gonna know my password!!';
$dbname = "galaxall";
$conn = new mysqli($servername, $username, $password, $dbname);
#mysql_select_db('galaxall');
?>
<?php $title =$_POST['myfile']?><br>
<?php echo $title?><br>
<?php echo $info?><br>
<?php echo $tags?><br>
<?php echo $category?><br>
<?php echo $allowcomments?><br>
<?php echo $visibility?><br>
<?php echo $flagging?><br>
<?php echo $cap ?>
<?php echo $date ?>
<?php echo $name ?>
<?php echo $size ?>
<?php echo $type ?>
<?php echo $sub ?>
<?php echo $cap ?>
<?php $file=$_POST['myfile']?>
<?php
$sql="INSERT INTO `galaxall_uploads` (`ID`, `Title`, `Producer`, `Description`, `Tags`, `Type`, `Category`, `Allow comments`, `Flag offensive comments`, `Date`, `Visibility`,`Size`,`Path`,`Subtitles_source`,`Captions_source`) VALUES (NULL, '$title', '', '$info', '$tags', '$type', '$category', '$allowcomments', '$flagging', '$date', '$visibility','$size','$path','$cap','$sub')";
$sql2="CREATE TABLE $title `Comments` ( `ID` BIGINT(255) NOT NULL AUTO_INCREMENT , `Commenter` VARCHAR(255) NOT NULL , `Comment` TEXT NOT NULL , `Date/time` DATETIME NOT NULL , `Likes` BIGINT(255) NOT NULL , `Dislikes` BIGINT(255) NOT NULL , `Replies number` BIGINT(255) NOT NULL , PRIMARY KEY (`ID`)) ENGINE = InnoDB;";
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
<?php
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn->query($sql2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
?>
<html>
The file has been uploaded
</html>
The var $title has been declared and I an even echo it.But when i try to make it the name of the table(sql2),I get the error
2018-07-20 New record created successfullyError: CREATE TABLE title `Commentsss` ( `ID` BIGINT(255) NOT NULL AUTO_INCREMENT , `Commenter` VARCHAR(255) NOT NULL , `Comment` TEXT NOT NULL , `Date/time` DATETIME NOT NULL , `Likes` BIGINT(255) NOT NULL , `Dislikes` BIGINT(255) NOT NULL , `Replies number` BIGINT(255) NOT NULL , PRIMARY KEY (`ID`)) ENGINE = InnoDB;
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 '`Commentsss` ( `ID` BIGINT(255) NOT NULL AUTO_INCREMENT , `Commenter` VARCHAR(25' at line 1 The file has been uploaded
So how do I make a PHP variable the name of a table?
i don't want to get in your database design but the error you are facing is about string concatenation and an issue on having a space in the table name:
$sql2="CREATE TABLE `$title_Comments` ( `ID` BIGINT(255) NOT NULL AUTO_INCREMENT , `Commenter` VARCHAR(255) NOT NULL , `Comment` TEXT NOT NULL , `Date/time` DATETIME NOT NULL , `Likes` BIGINT(255) NOT NULL , `Dislikes` BIGINT(255) NOT NULL , `Replies number` BIGINT(255) NOT NULL , PRIMARY KEY (`ID`)) ENGINE = InnoDB;";
this will fix the error you mention in your question
EDIT: looking at the comments I can suggest you to have a single table for comments where you store the comment, the id of the user that does the comment and the id of the video they are commenting on. As I said, no need for a custom table each time
I am trying to post data into two databases namely add_product and ledger but I keep getting the following error message:
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 'desc, amount)values('mnbvx', 'opening stock', '5')' at line 1
Below is my PHP code:
<?php
include ('session.php');
if($_GET["name"] && $_GET["opening"]&& $_GET["re"])
{
$servername="localhost";
$username="root";
$db="multiple";
$pass="";
mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$name=$_GET["name"];
$op=$_GET["opening"];
$re=$_GET["re"];
mysql_query("insert into add_product (product, opening, current, reorder)values('$name', '$op', '$op', '$re')");
mysql_query("insert into ledger (product, desc, amount)values('$name', 'opening stock', '$op')")or die(mysql_error());
print "<h4>product added to database</h4>";
print "<p><a href='add_pdt.html'>add another?</a></p>";
print "<a href='index_admin.php'>home</a>";
}
else{
print "please fill all fields correctly";
print " ";
print "<p><a href='add_pdt.html'>back</a></p>";
print "<p><a href='index_admin.php'>home</a></p>";
}
?>
below is - Table structure for table `ledger`
CREATE TABLE IF NOT EXISTS `ledger` (
`product` varchar(60) NOT NULL,
`desc` varchar(60) NOT NULL,
`amount` varchar(15) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
below --
-- Table structure for table `add_product`
CREATE TABLE IF NOT EXISTS `add_product` (
`product` varchar(30) NOT NULL,
`id` int(30) NOT NULL,
`opening` int(100) NOT NULL,
`current` int(100) NOT NULL,
`reorder` int(6) NOT NULL,
`updateon` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=93 ;
--
Use this query instead of your second query.
mysql_query("insert into ledger (`product`, `desc`, `amount`)values('$name', 'opening stock', '$op')")or die(mysql_error());
DESC is a reserved keyword. Either use backticks around it:
`desc`
or rename it.
desc is resevered ... and mysql is depricated...
use
$con = ('localhoat','root','','database_name');
mysqli_query($con,"insert into ledger (`product`, `desc`, `amount`)values('$name','opening stock', '$op')")or die(mysql_error()");