This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
Error: INSERT INTO grocery ('GrocerID', 'GrocerName', 'Address',
'LogoImage') VALUES ('GID0072', 'BigBazaar','India, Andhra Pradesh,
522124','WIN_20150817_121614.JPG') 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 ''GrocerID', 'GrocerName', 'Address',
'LogoImage') VALUES ('GID0072', 'BigBazaar' at line 1
<?php
$servername = "localhost";
$username = "root";
$password = "secret";
$dbname = "task";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$GrocerID=$_POST['GrocerID'];
$GrocerName=$_POST['GrocerName'] ;
$Address=$_POST['Address'];
$LogoImage=$_POST['LogoImage'] ;
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO grocery ('GrocerID', 'GrocerName', 'Address', 'LogoImage')
VALUES ('$GrocerID', '$GrocerName','$Address','$LogoImage')";
if ($conn->query($sql) === TRUE) {
header('Location:task.html');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Data Base image
Can someone please tell me what the mistake I'm doing here??
I have used
database name: task,
table name: grocery
But i'm not able to understand where I'm doing the mistake.
Thankyou
not write coloumn in '' use backticks ``
INSERT INTO grocery
(GrocerID, GrocerName, Address, LogoImage)
VALUES ('GID0072', 'BigBazaar','India, Andhra Pradesh, 522124','WIN_20150817_121614.JPG')
Either Remove '
INSERT INTO grocery
(GrocerID, GrocerName, Address, LogoImage)
VALUES ('GID0072', 'BigBazaar','India, Andhra Pradesh, 522124','WIN_20150817_121614.JPG')
OR
Replace ' with ` (backtick)
[NOTE: You can find backtick below Esc key in keyboard]
INSERT INTO grocery
(`GrocerID`, `GrocerName`, `Address`, `LogoImage`)
VALUES ('GID0072', 'BigBazaar','India, Andhra Pradesh, 522124','WIN_20150817_121614.JPG')
And, Use real_escape_string() to prevent SQL Injection Attacks
PHP provides real_escape_string() to escape special characters in a
string before sending a query to MySQL. This function was adopted by
many to escape single quotes in strings and by the same occasion
prevent SQL injection attacks. However, it can create serious security
flaws when it is not used correctly.
$GrocerName = $conn->real_escape_string($_POST['GrocerName']);
$Address = $conn->real_escape_string($_POST['Address']);
$LogoImage = $conn->real_escape_string($_POST['LogoImage']);
$sql = "INSERT INTO grocery (`GrocerID`, `GrocerName`, `Address`, `LogoImage`)
VALUES ('$GrocerID', '$GrocerName','$Address','$LogoImage')";
Do not use quotes for column_name.
Related
I'm stuck with a syntax error for a SQL query to insert data into a table.
Ah, the syntax error, most useless of all errors!!
Using the code modified from PHP Insert Data Into MySQL using both mysqli and PDO methods.
e.g.:
<?php
$servername = "localhost";
$username = "4w_write";
$password = "GjByhJzrQueHgTzw";
$dbname = "4w_test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO 4w (email) VALUES ($email)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Having stripped it down to a single variable which isn't using a keyword, I'm pretty sure the problem is with my table.
SQL Query:
INSERT INTO 4w (email) VALUES (myemail#gmail.com)
Error:
Error: INSERT INTO 4w (email) VALUES (myemail#gmail.com) 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 '#gmail.com)'
at line 1
SQL table (4w):
# Name Type Default
1 id [Primary,Index] int(11)
2 email varchar(255)
3 whatIs tinytext
4 whereIs text
5 whattodo text
6 imageURL text
7 whenRep timestamp CURRENT_TIMESTAMP
The email value is a string, so you need to surround it with quotes:
$sql = "INSERT INTO 4w (email) VALUES ('$email')";
Or, better yet, use a prepared statement and bind it's value.
Couldn't see the problem, missing quotes....
Original code:
$sql = "INSERT INTO 4w (email) VALUES ($email)";
Fixed code:
$sql = "INSERT INTO 4w (email) VALUES ('$email')";
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I'm new on StackOverflow. Hope I'm doing the questioning correctly.
I'm trying to insert data from an external XML (URL) into an SQL table, but I get:
Error: INSERT INTO 'table_name' ('price')VALUE ('5.95')
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 ''BBB' ('price')VALUE ('5.95')' at line 1
I'm able to ECHO and PRINT values from the XML and also able to INSERT non-xml values into the table. The code I'm using is:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$xml=simplexml_load_file("external_xml_url") or die("Error: Cannot create object");
foreach ($xml->product as $row) {
$price = $row -> price;
$sql = "INSERT INTO 'table_name' ('price')"
. "VALUES ('$price')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Would be great if someone can help me out on this one. I've the feeling I'm pretty close...
As far as I know, with MariaDB you have to use Backticks to "qoute" an object's name.
Try it like this:
$sql = "INSERT INTO `table_name` (`price`) VALUES ('$price')";
If you do not deal with dangerous object names you might use just
$sql = "INSERT INTO table_name (price) VALUES ('$price')";
If you got your price properly then you should check your query
Ex.
INSERT INTO table_name (price) VALUES ('$price')
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I've recently trying to add data into a database, (New to php), I've looked over to see where I've gone wrong, but can't find anything. The error is:
Unknown column 'FUMUKU' in 'field list'
Code:
$dbhost = 'localhost';
$dbuser = 'evocityi_admin';
$dbpass = 'password';
$database = 'evocityi_stocks';
$conn = mysql_connect($dbhost, $dbuser, $dbpass, $database);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$Dtime = "30/04/16";
$StockName = "FUMUKU";
$FUMUKUPrice = 1000;
$sql = "INSERT INTO stocks".
"(Stock,Price, TimeD) ".
"VALUES ".
"('$StockName,$FUMUKUPrice, $DTime')";
mysql_select_db('evocityi_stocks');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
SQL Database:
https://gyazo.com/fc97b686cfea79ea773d1796e912551e
Use this It will helps you.
$sql = "INSERT INTO stocks(Stock,Price,TimeD) VALUES ('$StockName','$FUMUKUPrice', '".date('Y-m-d',strtotime($Dtime))."')";
'$StockName,$FUMUKUPrice, $DTime'
You should surround every variable with quotes:
'$StockName' ,' $FUMUKUPrice' , '$DTime'
Just know that when blindly concatenating variables into a SQL query and not preparing statements for user input makes your code vulnerable to SQL injection. Use Prepared Statements instead. Also, use the mysqli_* functions, the mysql_* functions are deprecated.
Try this query, you are not using qoutes properly on the variables due to this It through error.
$sql = "INSERT INTO stocks".
"(Stock,Price, TimeD) ".
"VALUES ".
"('".$StockName."', '".$FUMUKUPrice."', '".$DTime."')";
To avoid deprecation and SQL Injection you should use PDO or mysqli.
You're using mysql_* functions, that's what's wrong.
Read the documentation and look into alternatives.
One such alternative may be:
$query = $pdoconnection->prepare("
insert into `stocks`
(`Stock`,`Price`,`TimeD`)
values (?,?,?)
");
$query->execute([$StockName, $FUMUKUPrice, $Dtime]);
Try this
$sql = ("INSERT INTO stocks (Stock,Price, TimeD)
VALUES('$StockName', '$FUMUKUPrice', '$DTime')");
I managed to fix it using:
$sql = "INSERT INTO `stocks` (`Stock`,`Price`, `TimeD`) VALUES ('$StockName','$FUMUKUPrice', '".date('Y-m-d',strtotime($Dtime))."')";
I have a php statement to insert a bit of information into my mySQL database. the connection works perfectly. The problem I am having is I am getting the following error code:
Error: INSERT INTO tasks ('taskName', 'requestedBy', 'details',
'dateAdded') VALUES ('test1' ,'test3' ,'test3', 2015-01-05') 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 ''taskName',
'requestedBy', 'details', 'dateAdded') VALUES ('test1' ,'test3' ,'te'
at line 1
the function is as follows
if(isset($_POST["submitTask"])){
insertTask();
};
function insertTask(){
$servername = "localhost";
$username = "tasktrack";
$password = "";
$dbname = "tasktrack";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$taskname = $_POST["task_name"];
$requestedby= $_POST["requested_by"];
$details = $_POST["details"];
$datenow = date("Y-m-d");
$sql = "INSERT INTO tasks ('taskName', 'requestedBy', 'details', 'dateAdded') VALUES ('$taskname' ,'$requestedby' ,'$details', $datenow')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
};
I have tried multiple different solution with the $sql line as seen below
$sql = "INSERT INTO tasks ('taskName', 'requestedBy', 'details', 'dateAdded') VALUES ('$taskname' ,'$requestedby' ,'$details', $datenow')";
$sql = "INSERT INTO tasks (taskName, requestedBy, details, dateAdded) VALUES ($taskname ,$requestedb ,$details, $datenow)";
$sql = "INSERT INTO tasks (`taskName`, `requestedBy`, `details`, `dateAdded`) VALUES (`$taskname` ,`$requestedb` ,`$details`, `$datenow`)";
Now I am just stuck and can't think of any more things to try.
$sql = "INSERT INTO tasks (taskName, requestedBy, details, dateAdded) VALUES ('$taskname' ,'$requestedby' ,'$details', '$datenow')";
// Removed quotes from columns, and added missing quote on datenow
Please note, this technique for adding values into the database is very insecure, and is prone to SQL injection attacks.
You must not enclose the field names in apostrophes or quotes. Either enclose them in back quotes (`) or use them as they are.
$sql = "INSERT INTO tasks (`taskName`, `requestedBy`, `details`, `dateAdded`) VALUES ('$taskname' ,'$requestedby' ,'$details', '$datenow')";
or
$sql = "INSERT INTO tasks (taskName, requestedBy, details, dateAdded) VALUES ('$taskname' ,'$requestedby' ,'$details', '$datenow')";
However, if the field name is a MySQL keyword or if it contains spaces, quotes, commas, parenthesis, operators or other characters that have special meaning in SQL then you have to enclose them in back quotes or MySQL will report a syntax error at the special character.
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 8 years ago.
I am trying to insert a sample blog post into my 'posts' table in MySQL (using PHP) however I receive a syntax error whenever a large character post is submitted. If I submit content of say 20 characters it works but something like 500 characters will throw the following error:
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 ''uid', 'username', 'p_date', 'title', 'content') VALUES('1','Mark Twain', '2014-' at line 1
The 'content' is to be inserted into the database via a varchar(1000) variable. The table is defined in mysql as:
CREATE TABLE posts
(
pid int NOT NULL AUTO_INCREMENT,
uid int NOT NULL,
username varchar(100) NOT NULL,
p_date date NOT NULL,
title varchar(225) NOT NULL,
content varchar(10000) NOT NULL,
PRIMARY KEY(pid),
FOREIGN KEY(uid) REFERENCES users(uid)
);
The actual content I am trying to submit is this:
Secondly, these missionaries would gradually, and without creating suspicion or exciting alarm, introduce a rudimentary cleanliness among the nobility, and from them it would work down to the people, if the priests could be kept quiet. This would undermine the Church. I mean would be a step toward that. Next, education -- next, freedom -- and then she would begin to crumble. It being my conviction that any Established Church is an established crime, an established slave-pen, I had no scruples, but was willing to assail it in any way or with any weapon that promised to hurt it. Why, in my own former day -- in remote centuries not yet stirring in the womb of time -- there were old Englishmen who imagined that they had been born in a free country: a "free" country with the Corporation Act and the Test still in force in it -- timbers propped against men's liberties and dishonored consciences to shore up an Established Anachronism with.
The insert statement for this is the following:
$sql = "INSERT INTO posts ('uid', 'username', 'p_date', 'title', 'content') VALUES('$uid','$uname', '$date', '$title', '$content')";
if(!mysql_query($sql,$con)){
echo "Oops! Something went wrong during the posting process. Please try again. ";
die('Error: ' . mysql_error($con));
header('Refresh: 1; URL=postingform.php');
}else{
// Now return the user to their post page
header('Refresh: 0; URL=postlist.php?uid='.$uid.'');
}
For some reason it is error-ing out during the INSERT process. The one thing strange I notice is that the date is cut off in the error. To call the date I am using. $date = date("Y-m-d");
I have used this same syntax before without issues.
****Edit
A few posters have pointed out that there are single quotations in my INSERT column statements. I have changed these to back tics and completely removed them but the error still results.
New Error:
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 's Court', 'Secondly, these missionaries would gradually, and without creating su' at line 1
There is something still wrong with my insert syntax but everything I am reading says it should be correct.
$sql = "INSERT INTO posts (`uid`, `username`, `p_date`, `title`, `content`) VALUES('$uid','$uname', '$p_date', '$title', '$content')";
Remove all the quotes in (for your columns)
('uid', 'username', 'p_date', 'title', 'content')
Those aren't the correct column identifiers
http://dev.mysql.com/doc/refman/5.5/en/identifiers.html
use
(uid, username, p_date, title, content)
or use backticks.
(`uid`, `username`, `p_date`, `title`, `content`)
However and as a quick FYI, backticks are mostly used for reserved keywords, or if a table/column contains spaces, hyphens.
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
The error message was letting you know here
check the manual that corresponds to your MySQL server version for the right syntax to use near ''uid',
^--« right there
Notice the quote just before 'uid'? That's where the problem starts.
Edit:
Try the following using prepared statements and replace xxx with your own credentials.
This should take care of the quotes issue from your input values.
You will need to add the variables according to your inputs.
<?php
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}
$uid = ""; // replace with proper value
$uname = ""; // replace with proper value
$date = ""; // replace with proper value
$title = ""; // replace with proper value
$content = ""; // replace with proper value
$stmt = $conn->prepare("INSERT INTO posts (`uid`, `username`, `p_date`, `title`, `content`) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param('sssss', $uid, $uname, $date, $title, $content);
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
else{
echo "Success";
}
$stmt->close(); // Statement
$conn->close(); // MySQLi
Footnotes:
In order to allow single and/or double quotes, based yourself on the following, while using the stripslashes() function.
$content = stripslashes($_POST['content']);
This will enter in DB properly:
Bob's sister was here today and said: "Bob, what lovely hair you have!".