Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I am trying to escape fields posted from a form. I can successfully insert into the SQL database by commenting out the code that escapes the string.
The error received is:
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\",\"0123456789\",\"test#test.com\",\"1\",\"1\",\"fgsdfdfndfndfndfndfndfn\' at line 1
Here is the code I am using:
$Name= $_POST['fullname'];
$Phone = $_POST['phone'];
$email = $_POST['email'];
$inBuilding = $_POST['inbuilding'];
$floor = $_POST['floor'];
$inRoom = $_POST['inroom'];
$majorDescription = $_POST['majorcategory'];
$description = $_POST['desc'];
$query = "INSERT INTO `problem`.`reports` (`Name`, `PhoneNumber`, `EmailAddress`, `inBuilding`, `inRoom`, `Description`, `MajorDescription`) VALUES (";
$query .= '"' . $Name. '","' . $Phone . '","' . $email . '","' . $inBuilding . '","' . $inRoom . '","' . $description . '","' . $majorDescription . '");';
$query = mysqli_real_escape_string($connect, $query);
I have also tried:
$query = mysqli_escape_string($connect, $query);
with the same error.
According to other examples on stack overflow I changed the INSERT INTO code to the following:
$query = "INSERT INTO `problem`.`reports` (Name, PhoneNumber, EmailAddress, inBuilding, inRoom, Description, MajorDescription) VALUES ('$Name', '$Phone', '$email', '$inBuilding', '$inRoom', '$description', '$majorDescription')");
This code gave server 500 error.
MySQL is fully updated.
Any assistance appreciated!
MikeW's solution worked. Also realized I was trying to escape the string before I had opened the database making mysqli_real_escape_string return null. Connecting to the database first, ($connect= new connect("server","user","password");) solved this problem. Hopefully this will help anyone else with the same problems.
You should be using single quotes, not double quotes. Also, mysqli_real_escape_string() should be called on each variable, not on the query as a whole. You should get something like this:
$Name= mysqli_real_escape_string($connect, $_POST['fullname']);
// more variables, similarly escaped.
$query = "INSERT INTO `problem`.`reports` (`Name`, `PhoneNumber`, `EmailAddress`, `inBuilding`, `inRoom`, `Description`, `MajorDescription`) VALUES (";
$query .= "'$Name','$Phone','$email','$inBuilding','$inRoom','$description','$majorDescription')";
However, for this sort of query you should consider using prepared statements.
I'm not sure if MySQL works with double-quotes. You should use single-quotes. But the more glaring issue is that you need to call mysqli_real_escape_string() on every variable, not the entire query string.
To simplify the problem, say your query was as follows:
$query = "INSERT INTO tbl (Name) VALUES ('". $_POST['name'] ."')";
$query = mysqli_real_escape_string($connect, $query);
And then say I pass in a value, Michael O'Connor. What does your query become?
INSERT INTO tbl (Name) VALUES (\'Michael O\'Connor\')
Notice that not only did the ' in the actual name get escaped, but the quotes to surround that name also got escaped. If you called mysqli_real_escape_string() on the entire compiled query string, it has no way to distinguish a ' in the value vs. the ones that are supposed to surround the value.
Related
$firstName = mysqli_real_escape_string($dbcon, $_POST['newFirstName']);
$lastName = mysqli_real_escape_string($dbcon, $_POST['newLastName']);
$emailAddress = mysqli_real_escape_string($dbcon, $_POST['newEmailAddress']);
$sqlQuery = "INSERT INTO admins (firstname, lastname, email) VALUES ('$firstName','$lastName','$emailAddress')
ON DUPLICATE KEY UPDATE firstname ='".$firstName."' lastname='".$lastName."' email='".$emailAddress."'";
My issue is on the last line. AFAIK you have to use double quotes for PHP to actually insert your variable into the string, but no matter what quotes I use I get errors. What's the proper syntax for inserting the variables?
You are missing commas from your SQL query in between the parameters you are updating.
Additionally for your update statement, you need to specify the table and SET:
"Update admins
Set firstname = '". $firstname . "' , lastname = '" . $lastname . "' " etc.
You should separate the columns you're updating with a comma. e.g:
ON DUPLICATE KEY UPDATE firstname ='".$firstName."', lastname='".$lastName."',
email='".$emailAddress."'";
I'm having trouble specifying my tablename inside the following query.
$sql = "INSERT INTO db269193_crud.posts (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
The tablename is: db269193_crud.posts. I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
So the table name becomes: db269193(dot)posts. This dot however keeps lighting up in my editor as an incorrect syntax.
I need someone's help to tell me if I specified the table name correctly or if I have to use a variable to hide the dot notation like:
$tablename = 'db269193.crud';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You can put the entire name in backticks to escape it:
INSERT INTO `db269193_crud.posts` (post_title, description)
VALUES ('" . $title . "', '" . $description . "')
As for the rest of your statement, I would encourage you to use parameters instead of munging the query string. By putting random strings in the query, you are just inviting syntax errors and SQL injection attacks.
I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
I pretty much doubt that as it would require DB changes which simply make no sense. I assume that it's your fault as you did not select DB to use in the first place. Check how you connect and ensure you provide DB name as well or at least you mysqli_select_db() or equivalent.
$tablename = 'db269193.crud';
You can use backticks when name of table or column conflicts or is reserved word:
$tablename = '`db269193.crud`';
or
$tablename = '`db269193`.`crud`';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You are complicating simple strings with unnecessary concatentation. This will work and is less error prone:
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('{$title}','{$description}')";
however you are still seem to be vulnerable to sql injection here. I'd recommend switching to PDO.
I am having an issue with my code not updating an existing computers data. If i remove the ON Duplicate section the code works fine and adds the data. i have made computer my unique key in my xampp data base. any help would be greatly appreciated.
<?php
$receive = htmlspecialchars($_POST['time']);
list($length, $status, $computer) = split(":", $receive, 3);
include('connection.php');
mysqli_query($dbc, "INSERT INTO screen(computer,status,length)
VALUES('$computer','$status','$length')
ON DUPLICATE KEY UPDATE
status=$status, length=$length");
?>
A better pattern for creating a SQL statement which mitigates some common SQL Injection vulnerabilities. Also note that the special VALUES() function can be used to reference the values that would have been inserted for a column, if the insert had succeeded.
$sql = "INSERT INTO screen(computer,status,length)
VALUES('"
. mysqli_real_escape_string($dbc,$computer)
. "','"
. mysqli_real_escape_string($dbc,$status)
. "','"
. mysqli_real_escape_string($dbc,$length)
. "')
ON DUPLICATE KEY UPDATE
status=VALUES(status), length=VALUES(length)";
mysqli_query($dbc,$sql);
I am trying to insert the results from a json array into MySQL using
foreach ($feed->items as $item) {
$query = "insert into data(id,url,keyword)values ($item->id, $item->url,$item->kind)";
$result = mysql_query($query);
echo $result;
}
I have confirmed the database details are OK and the $items are correct.
Can anyone point me in the right direction? I am fairly new to PHP so any help is appreciated.
You need to escape the values in the SQL:
$query = "insert into data(id,url,keyword)values ('" . mysql_real_escape_string($item->id) . "', '" . mysql_real_escape_string($item->url) . "' , '". mysql_real_escape_string($item->kind) . "')";
this adds quotation marks ' around the variables so that the SQL can be parsed at all
This prevents SQL injection.
You need to wrap your variabels in your query :
$query = "insert into data(id,url,keyword)values ('{$item->id}', '{$item->url}', '{$item->kind}')";
Hy all,
Not sure what's going on here, but if I run this:
$query = 'INSERT INTO users
(`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES
("'. $user_id . '", "' . $first_name .'", "'. $second_name . '", "' . $date . '", "' . $date . ");';
$result = mysql_query($query);
I get no return, but if I change it to this it's fine:
$query = 'INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES ("21021212", "Joe", "Bloggs", "20090202", "20090202");';
$result = mysql_query($query);
User id = bigint(20)
first name = varchar(30)
second name = varchar(30)
date = int(8)
At first I thought it was a issue with the vars but they are exactly the same and still don't work.
Any help appreciated.
Get into the habit of escaping all database inputs with mysql_real_escape_string- really, you should use some kind of wrapper like PDO or ADODb to help you do this, but here's how you might do it without:
$query = sprintf("INSERT INTO users ".
"(id, first_name, second_name, register_date, lastlogin_date)".
"VALUES('%s','%s','%s','%s','%s')",
mysql_real_escape_string($user_id),
mysql_real_escape_string($first_name),
mysql_real_escape_string($second_name),
mysql_real_escape_string($date),
mysql_real_escape_string($date));
$result = mysql_query($query);
and also check for errors with mysql_error
if (!$result)
{
echo "Error in $query: ".mysql_error();
}
What's the result from "mysql_error()"? Always check this, especially if something doesn't seem to be working.
Also, echo out $query to see what it really looks like. That could be telling.
Maybe the value of $date was "1111'); DELETE FROM users;"?
Seriously though? The problem is that isn't how you interact with your database. You shouldn't be passing in your data with your query. You need to specify the query, the parameters for the query, and pass in the actual parameter values when you execute the query. Anything else is inefficient, insecure and prone to bugs like the one you have.
By using PDO or something that supports parametrized queries, you'll find these kinds of issues go away because you are calling the database property. It is also much more secure and can speed up the database.
$sth = $dbh->prepare("INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`) VALUES (?,?,?,?,?)")
$sth->execute(array($user_id ,$first_name , $second_name , $date, $date ));
In addition to echoing the query and checking mysql_error() as #GoatRider suggests:
Are you escaping your data properly? See mysql_real_escape_string()
You shouldn't end your queries with a semicolon when using mysql_query()
in $query = 'INSERT INTO users (id, first_name, second_name, register_date, lastlogin_date) VALUES ("' . $user_id . '", "' . $first_name . '", "' . $second_name . '", "' . $date . '", "' . $date . '");
are u giving the correct date format?? it might be the issue. otherwise the syntax is all fine.