SQL syntax error, I just can't see it - 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
}
?>

Related

mysql query is not working i had many try

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

PHP, MYSQL error?

i recently started working with PHP and MYSQL, everything was going fine till I starter to get this error. Code works when I insert it into the query window at phpMyAdmin, but it doesnt work inside php code when i open it with a browser. Im already connected to database, so thats not the problem.
this is the error i get:
SQLSTATE[42000]: Syntax error or access violation: 1064 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 ''fatmam' (user,
messageid) VALUES ('ayihan', '5')' at line 1
try
{
$alicengiz = $_POST['actor'].'m';
$sql = 'INSERT INTO :tablename (user, messageid) VALUES
(:user, :messageid)';
$s = $pdo->prepare($sql);
$s->bindValue(':user', $_SESSION['username']);
$s->bindValue(':messageid', $_POST['action1']);
$s->bindValue(':tablename', $alicengiz);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error 1qqq. '. $e->getMessage();
include 'error.php';
exit();
}
No. You cannot prepare table names, field names and sql keywords.
Problem is, that prepare() will add single quotes around the input, but table names and field names require backticks around them when you want to escape them.
This time you need to escape manually (*real_escape_string doesn't help here):
$sql = 'INSERT INTO `'.addcslashes($alicengiz, "\\'").'` (user, messageid) VALUES
(:user, :messageid)';
$s = $pdo->prepare($sql);
$s->bindValue(':user', $_SESSION['username']);
$s->bindValue(':messageid', $_POST['action1']);
P.s.: but really, this is a bad idea. I'd use a whitelist instead of escaping, because when $_POST["actor"]."m" isn't a table name, a PDOException will be thrown.
How about this?
$alicengiz = $_POST['actor'].'m';
$sql = 'INSERT INTO messages (user, messageid) VALUES
(:user, :messageid)';
$s = $pdo->prepare($sql);
$s->bindValue(':user', $_SESSION['username']);
$s->bindValue(':messageid', $_POST['action1']);
$s->execute();

mySQL query syntax error?

I have contact form at my wordpress site which is delivered by ajax, and sent to my mail. I also wanted to save the results in a database so I wrote this query, but it gives me and syntax error, but I can't find anything wrong in this code:
<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("u31272B3", $con);
$sql="INSERT INTO wp_contactform (Nimi, Puhelin, E-mail, Viesti, IP, Day)
VALUES
('$_POST[Nimi]','$_POST[Puhelin]','$_POST[Sposti]','$_POST[Tiedot]','$_POST[Gotcha]','$_POST[Day]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
The jquery script that sends it works, and the mail is sent, but this doesn't save.
Quote the column name E-mail with backticks (`). MySQL is interpreting this in two parts at the moment.
Note also, (as per my comment) that your code is wide open to SQL injection attacks. It is much better to use properly parameterised SQL queries.
SQL injection example:
"INSERT INTO table (field) VALUE ('$_POST[var]')"
If you post the value "'; DROP TABLE table; --" then you have a valid SQL string that inserts an empty string, then attempts to drop the table. Substitute whatever harmful statement you want.
and also you should use mysql_real_escape_string() or prepared statements. if your query data have any special characters it can blow your query it also help you from sql injection too.
http://php.net/mysql_real_escape_string
http://php.net/pdo
Your SQL request should be written as below:
$sql = "INSERT INTO wp_contactform (`Nimi`, `Puhelin`, `E-mail`, `Viesti`, `IP`, `Day`)
VALUES
('$_POST[Nimi]','$_POST[Puhelin]','$_POST[Sposti]','$_POST[Tiedot]','$_POST[Gotcha]','$_POST[Day]')"
SQL fields using non-alphanumeric characters have to be escaped with backticks (`)
This should work
<?php
$con = mysql_connect("localhost", "username", "password");
if(!$con){
die('Could not connect: '.mysql_error());
}
mysql_select_db("u31272B3", $con);
$sql = "INSERT INTO wp_contactform (`Nimi`, `Puhelin`, `E-mail`, `Viesti`, `IP`, `Day`)
VALUES
('".mysql_real_escape_string($_POST['Nimi'])."','".
mysql_real_escape_string($_POST['Puhelin'])."','".
mysql_real_escape_string($_POST['Sposti'])."','".
mysql_real_escape_string($_POST['Tiedot'])."','".
mysql_real_escape_string($_POST['Gotcha'])."','".
mysql_real_escape_string($_POST['Day'])."')";
if(!mysql_query($sql, $con)){
die('Error: '.mysql_error());
}
echo "1 record added";
mysql_close($con);

Cannot submit form to database

I am working with WordPress and I made a form in the admin section. I am trying to submit it to another database (not the default wp one) so I switch databases successfully and do an insert query but I keep getting an error.
This is my code:
$selected = mysql_select_db( 'petracms', $serverAccess );
if (!$selected) {
die ('Can\'t use foo : ' . mysql_error());
}
$query = "INSERT INTO `petra_customers` (`FirstName`, `LastName`, `Email`, `Phone`) VALUES ($fName, $lName, $email, $phone)";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
I keep getting this error:
Invalid query: 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 '#gmail.com, 5859475566)' at line 1
This is my input: (Adam, Page, bofumme#gmail.com, 5859475566)
I have no idea what I am doing wrong
Values in INSERT statements need to be enclosed in quotes (except "numbers"):
INSERT INTO `foo` (`a`,`b`,`c`) VALUES("foo","bar",1)
This is how you would (safely) construct a variable for use in query string interpolation (this is frowned upon, though):
$email = sprintf('"%s"', mysql_real_escape_string($_POST['email']));
$query = "INSERT INTO `foo` (`email`) VALUES($email)";
A more elegant way (and far more secure, too), is to use prepared statements (example uses PDO):
# Prepare the statement
$sth = $dbh->prepare('INSERT INTO `foo` (`email`) VALUES(:email)');
# Substitute placeholders in query and execute it
$sth->execute(array(
'email' => $_POST['email']
));
I guess you forgot to add quotes ' to your INSERT query. Check out any tutorial on the web on how to do simple inserts, eg here: http://www.w3schools.com/php/php_mysql_insert.asp

INSERT INTO database table, from form not working. SQL

lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):
"Connected to databaseError: 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 ''test' ('name') VALUES ('daniel')' at line 1"
The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?
Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.
HTML
<form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>
PHP (insert.php)
<?php
$dbhost = 'localhost';
$dbname = 'carbon_db';
$dbuser = 'username';
$dbpass = 'password';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if($con == FALSE)
{
echo 'Cannot connect to database' . mysql_error();
}
else
{
echo 'Connected to database';
}
mysql_select_db($dbname, $con);
$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Drop the quotes around the table name or change them to back ticks:
Change:
$sql="INSERT INTO 'test' ('name') VALUES ('$_POST[namefield]')";
To:
$sql="INSERT INTO test ('name') VALUES ('$_POST[namefield]')";
Or
$sql="INSERT INTO `test` ('name') VALUES ('$_POST[namefield]')";
It's often best to use backticks for MySQL as like any other storage engines it has it's own reserved names and it's own reserved insert practices.
try with
$sql = "INSERT INTO `test` (`name`) VALUES ('".$_POST['namefield']."')";
Change the single quotes surrounding the table name and the column name to backticks. Or get rid of them all together.
$sql="INSERT INTO `test` (`name`) VALUES ('{$_POST['namefield']}')";
Also, don't reference associative arrays ($_POST) directly in a string without using {} syntax or breaking up the string - what you have done there issues an E_NOTICE and should be avoided.
Read this thoroughly - you'd be amazed what you can (and can't) legally do in PHP strings...
try using ` instead of ' when refering to table/column names
$sql="INSERT INTO `test` (`name`)
VALUES ('$_POST[namefield]')";
Remove the single quotes around your sql statement and replace with back-tics (not sure even they are necessary):
$sql="INSERT INTO `test` ('name')
VALUES ('$_POST[namefield]')";

Categories