this is mysql query that i wanted to store date and time whenever a user come and
post comments over my website. But it showing me this context:
"Parse error: syntax..
code'error, unexpected 'now' (T_STRING) in"
$qry1='insert into life(title,quotation,photos,datetime) values('.$title.','.$quotation.','.$vphoto.''now())';'
I assume you are using PHP. When running queries, you should make use of prepared statements as it comes with a lot of benefits such as:
Reduced parsing time in that the preparation of your query is done only once.
SQL injection prevention.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check that your connection was successful
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$qry1 = $conn->prepare("INSERT INTO life (title, quotation, photos, datetime) VALUES (?, ?, ?, NOW())");
$qry1->bind_param("sss", $title, $quotation, $vphoto);
// set parameters and execute
$title = "Lorem Ipsum";
$quotation = "Lorem Ipsum";
$vphoto = "lorem#ipsum.com";
$qry1->execute();
$qry1->close();
$conn->close();
In php if you are using single quote 'x' then inside this you have to usedouble quote " " . Like this
$q = ' xyz("djch")' to maintain the escape sequence.
For your query you should use the curly braces to wrap the variables in php.
$q = "INSERT INTO life (v1,v2,v3) VALUES ('{$v1}','{$v2}','{$v3}')";
If you're looking to store the current time just use MYSQL's functions.
mysql_query("INSERT INTO `table` (`dateposted`) VALUES (now())");
If you need to use PHP to do it, the format it Y-m-d H:i:s so try
$date = date('Y-m-d H:i:s');
mysql_query("INSERT INTO `table` (`dateposted`) VALUES ('$date')");
your Code:
$qry1='insert into life(title,quotation,photos,datetime) values('.$title.','.$quotation.','.$vphoto.''now())';'
change to this:
$qry1="insert into life(title,quotation,photos,datetime) values('.$title.','.$quotation.','.$vphoto.', now())';'
$qry1='insert into life(title,quotation,photos,datetime) values("'.$title.'","'.$quotation.'","'.$vphoto.'", now())';
try above code if you use single codes on values('.$title .') compiler will thing start point of query is near 'insert AND end point is near 'title
Try this. You have misused single quotes and concatenation.
$qry1 = "INSERT INTO life ( title, quotation, photos, datetime ) VALUES('$title', '$quotation', '$vphoto', NOW())";
Note: Your query is wide open to Sql Injections. Learn about prapared statements or PDO
Related
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I'm attempting to insert some data into a table using mysqli functions.
My connection works fine using the following:
function connectDB(){
// configuration
$dbuser = "root";
$dbpass = "";
// Create connection
$con=mysqli_connect("localhost",$dbuser,$dbpass,"my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}else{
echo '<br />successfully connected<br />';
return $con;
}
}
But when I attempt to run my insert function I get nothing in the database.
function newUserInsertDB($name,$email,$password){
$con = connectDB();
// Prepare password
$password = hashEncrypt($password);
echo $password . "<br />";
// Perform queries
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ($name,$email,$password,0)");
// insert
mysqli_close($con);
}
I have been looking through the list of mysqli functions for the correct way to give errors but they all seem to be regarding the connection to the DB, not regarding success of an insert (and I can clearly see in my DB that it is not inserting.)
What would be the best way to debug? Which error handling shall I use for my insert?
I've tried using mysqli_sqlstate which gives a response of 42000 but I cannot see any syntax errors in my statement.
As mentioned in my comment, you would be better off using a prepared statement. For example...
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
$stmt->execute();
Using this, you don't have to worry about escaping values or providing quotes for string types.
All in all, prepared statements are much easier and much safer than attempting to interpolate values into an SQL string.
I'd also advise you to pass the $con variable into your function instead of creating it within. For example...
function newUserInsertDB(mysqli $con, $name, $email, $password) {
// Prepare password
$password = hashEncrypt($password);
// functions that "echo" can cause unwanted side effects
//echo $password . "<br />";
// Perform queries
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
return $stmt->execute(); // returns TRUE or FALSE based on the success of the query
}
The quotes are missing from the mysql statement from around the values. Also, you should escape the values before inserting them into the query. Do this way:
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ('".
mysqli_real_escape_string($con,$name)."','".
mysqli_real_escape_string($con,$email)."','".
mysqli_real_escape_string($con,$password)."',0)");
Regards
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!".
i'am beginner in php and i have problem in insertion query
if(isset($id)){
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'.$id .') ";
$result = mysql_query($qry);
}
I'am connected to the database but the query didn't work.
Why it is not working? how can i correct it?
Don't create queries this way. It is very vulnerable to SQL injection.
Use a prepared statement instead. A prepared statement is precompiled, hence will not be subject to SQL injection.
$id = 99;
$tax = 8;
$stmt = $mysqli->prepare("insert into user_to_birds(user_id,tax_id)values(?,?)"));
$stmt->bind_param("ii", $user, $tax);
$stmt->execute();
.. work on it ..
$stmt->close();
ii stands for two integers. After that first part of the binding, telling which type of variables you use in which order, can you add the values of those variables to the statement. The values will be escaped automatically using this method.
if(isset($id)){
$qry = "insert into user_to_birds(user_id, tax_id)values('1','$id') ";
$result = mysql_query($qry);
}
Work like a charm.
I think your single quotes should be double quotes:
$qry = "insert into user_to_birds(user_id,tax_id )values( 1 ,".$id .") ";
You are confusing strings in PHP with strings in SQL (which is, admittedly, easy to do).
For how to insert into there's a nice article here
http://www.w3schools.com/php/php_mysql_insert.asp
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
//not sure if this will make a difference buy i would try a space between tax_id) and values(
also, im not sure if the way youve done it is wrong but i would have written like this
if(isset($id))
{
$qry = "insert into user_to_birds (user_id, tax_id)
values( '1' ,'".$id ."') ";
$result = mysql_query($qry);
}
look at string concatination aswell either have
" ' ' ".$variable." ' ' ";
in that fashion
As others have said, it looks like you're not using string concatenation correctly in your query. Try changing your query to something like:
$qry = "INSERT INTO user_to_birds (user_id,tax_id) VALUES ( 1 ,'$id') ";
Another possibility is that your $id variable isn't set. Try printing out the variale before doing the isset() check and that will tell you if you need to look at an earlier point in your code.
Finally, I'd recommend you look at mysqli functions rather than mysql.
http://php.net/manual/en/book.mysqli.php
You have some confusion in quotes: your string in " ", your sql value in ' ', but when you concatenate you need to close your string and write dot and variable, after this you need write dot, open string quotes again and write text if it needed. Your mistake - you didn't close string (") before concatenation and this leads to misinterpretation of the code. In this case your code will look like:
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'" .$id ."') ";
But you can not use concatenation,you can do it simply: PHP allows write your variable $id in string, without use concatenation:
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'$id') ";
I am trying to do a couple of php insert queries into a relational database, but I am running into a bit of an issue. In order for this relation to work I need to grab the autoincremented value from the first query and then insert it into the second query so the relation between the two exists.
I have this:
$query2 = "INSERT into words values ('' ,'$name') ";
-- The first value listed as '' is the auto-incremented primary key --
$query3 = "INSERT into synonyms values ('' , '', $alias') ";
-- The first value listed is the auto incremented pk, the second value needs to be the fk or the pk from the first query, but I don't know how to place it there. --
Is there a way to do this? Any help would be appreciated.
Here an SQL Fiddle to help y'all out:
http://sqlfiddle.com/#!2/47d42
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO words(word) values ('word1')");
$last_id = mysql_insert_id();
mysql_query("INSERT INTO words(synonym_id,synonym) values ($last_id, "synonym1)");
?>
Reference: http://php.net/manual/en/function.mysql-insert-id.php
. . You should consider using PDO in most recent PHP versions for its modern features, such as prepared statements, so that you don't need to worry about SQL Injection or broken escaping functions.
. . Using transactions is also advisable if the follow up queries are mandatory for the record to be useful. Using transactions keeps your database clear of the garbage of any failed second or third queries.
. . Also, you can omit the Auto-Increment field when running the Insert Query if you list the other fields after the table name. I think it's a much more common pattern, like INSERT INTO table (field1, field2) VALUES ("value1", "value2"). I used it in the example below:
$pdo = new PDO('mysql:host=localhost;dbname=database', 'user', 'pass');
$pdo->beginTransaction();
try {
$prepared = $dbh->prepare('INSERT INTO words (fieldName) values (?)');
$prepared->execute(array($name));
$fID = $pdo->lastInsertId();
$prepared = $dbo->prepare('INSERT INTO synonyms (fieldName) Values (?, ?)';
$prepared->execute(array($fID, $alias));
$dbo->commit();
} catch(PDOExecption $e) {
$dbo->rollback();
print 'Error: '. $e->getMessage();
}
. . Note that this will not work with MSSQL as it doesn't support "lastInsertId".
. . Amplexos.
not sure if you're using MySQL native functions or not. If so the answer is to use mysql_last_id(). These functions are deprecated and are not adivsable to use.
EXAMPLE:
//escape your indata
$brand= mysql_real_escape_string($_POST['brand']);
$sql = "INSERT INTO cars(brand) VALUES('{$brand}')";
mysql_query($sql);
//find last id from query above
$id = mysql_last_id();
Try PDO instead:
PDO::lastInsertId
EXAMPLE:
$brand= $_POST['brand'];
$sql = "INSERT INTO cars(brand) VALUES (:brand)";
$query = $conn->prepare($sql);
$query ->execute(array(':brand'=>$brand));
$id = $conn->lastInsertId();
http://www.php.net/manual/en/book.pdo.php
Here is my code:
<?php
$con = mysql_connect("localhost","solidarity","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$sql="INSERT INTO show_reviews (username, date, content, show) VALUES (".addslashes($_POST[username]).",".addslashes($_POST[date]).",".addslashes($_POST[content]).",".addslashes($_POST[show]).")";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
So I have used fsprint and now I have just used the w3schools code and this is my output with both pieces of code:
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 'show) VALUES (Solidarity, 17:02 - Wed, 1st Aug 2012,Testing,kr1971)' at line 1
I use a very similar syntax for a commenting system and do not have this problem. If it helps also, I have tried on a local sql server and remote also, still no luck.
Please help me :(.
Put the values inside of single quotes:
$sql=" INSERT INTO show_reviews (username, date, content, show)
VALUES ('".addslashes($_POST[username])."','".addslashes($_POST[date])."','".addslashes($_POST[content])."','".addslashes($_POST[show])."')";
Additionally, as others have said show is a reserved keyword in MySQL. You can see the full list of reserved keywords for MySQL 5.5 at http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
You can quote reserved words using the backtick in order to be able to use them:
INSERT INTO show_reviews (username, date, content, `show`)
Quoting Identifiers:
http://dev.mysql.com/doc/refman/5.5/en/identifiers.html
And finally, to summarize the comments about using addslashes() for escaping. I will let Chris Shiflett explain why it is bad: http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string
You really should be jumping aboard the prepared statements/parameterized queries bandwagon with PDO or at minimum, MySQLi. Here is an example of how you query could look:
$dbh = new PDO($connection_string);
$sql = "INSERT INTO show_reviews (username, date, content, show) VALUES (?, ?, ?, ?)";
$stmt = $dbh->prepare($sql);
$stmt->execute(array($_POST['username'],
$_POST['date'],
$_POST['content'],
$_POST['show']
));
while ($row = $stmt->fetch()) {
print_r($row);
}
This is purely an example, it is still a good idea to do your sanitizing of $_POST variables and do your best to ensure the data you received is exactly what you were trying to get. These prepared statements take care of escaping for you properly and, if using PDO, the proper way for your specific database engine.
show is a mysql keyword. So, it cannot be a column name. You will have to escape it, if you want to use show as a column name.
show is a reserved keyword in SQL. You have to enclose it with backticks to use as a column name.
Please use this query
$sql= 'INSERT INTO show_reviews (username, date, content, show)
VALUES ("'.addslashes($_POST[username]).'",".'addslashes($_POST[date]).'","'.addslashes($_POST[content]).'","'.addslashes($_POST[show]).'")';
Your values need to be wrapped in quotes.
$sql="INSERT INTO show_reviews (username, date, content, show) VALUES ('".addslashes($_POST[username])."','".addslashes($_POST[date])."','".addslashes($_POST[content])."','".addslashes($_POST[show])."')";
Also show is a reserved word, so you need to encase it in backticks.
To elaborate on Sebastian's comment, use PDO: it is more resilient (or immune?) to SQL injection attacks. The code will look something like this:
<?php
try {
$handle = new PDO('mysql:host=localhost;dbname=myDatabaseName', 'username','password');
$prepared = $handle->prepare("INSERT INTO show_reviews (username, date, content, show) VALUES (?,?,?,?)");
if($prepared->execute(array($_POST['username'], $_POST['date'], $_POST['content'], $_POST['show']))) {
echo "1 record inserted...";
}else {
echo "insert failed...";
}
}catch(PDOException $ex) {
// error connecting to database
}
?>