Multiple Rows INSERT in MySQL - mysql

I'am trying to add multiple rows into DB using SQL and it goes wrong with a message
"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 ''imglist' ('urlImg', 'idProduct') VALUES('C//','1')('C//','1')('C//','1')('C//','1')' at line 1"
This is my code for this function
$sql = 'INSERT INTO \'imgList\' (\'urlImg\', \'idProduct\') VALUES';
for($i=0;$i<10;$i++){
$sql .= '(\'' . $_POST['urlImg'][$i] . '\',\''
. $_POST['idProduct'][$i] .'\')';
if ($i<count($_POST['urlImg']) - 1) {
$sql .= ',';
}
}

Well, first of all, like others said, never concatenate values into SQL string directly. Not only it puts you at risk of SQL injection, but also will fail if you have single quotes in your data.
If query you built fails, then output it using echo and examine it. That error you're seeing is because you put single quotes (') around your table and column names, which is wrong. You should either use backticks (`) or don't use anything - quotes are only for literal strings.
$sql = 'INSERT INTO `imgList` (`urlImg`, `idProduct`) VALUES ';
There are other problems with your code, though. for($i=0;$i<10;$i++){ will loop 10 times even if you only have 1 element in $_POST['urlImg'], resulting in errors. And judging by VALUES('C//','1')('C//','1')('C//','1')('C//','1') in error, this part of code:
if ($i<count($_POST['urlImg']) - 1) {
$sql .= ',';
}
doesn't even work properly, since commas aren't even inserted between (...). No idea why, though, it worked fine when I tried it myself, perhaps you didn't show something.

Related

Prepared statements in SQL query while saving JSON data in PHP

I have simple php code for parsing some data from a JSON file and saving them into mysql database. But it's showing following error:
Parse error: syntax error, unexpected 'my_name' (T_STRING) in C:\xampp\htdocs\mycode.php on line 25
My php code is following:
$sql = "INSERT INTO table1 (my_name, hobby, other) VALUES ($row['my_name'], $row['hobby'], $row['other'])"; //line 25
mysqli_query ($conn, $sql);
Why is it showing syntax error? Is there anything wrong in the query?
You need to enclose interpolated placeholders in curly braces, i.e. $row['my_name'] -> {$row['my_name']}:
$sql = "INSERT INTO table1 (my_name, hobby, other) VALUES ({$row['my_name']}, {$row['hobby']}, {$row['other']})";
This addresses only PHP syntax.
The SQL syntax error you get now is the next issue.
The simplest thing to "fix" this would be to include additional apostrophes around placeholders, i.e.
$sql = "INSERT INTO table1 (my_name, hobby, other) VALUES ('{$row['my_name']}', '{$row['hobby']}', '{$row['other']}')";
BUT DON'T DO THAT, since this code is an example of a classic SQL Injection vulnerability.
Consider using a prepared statement instead — this eliminates the PHP's string interpolation altogether.

Getting an error after using PHP & MySQL code

I get the usual errors ( already tried to read previous questions ) Query failedYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''','',now(),'','This is great! ','', 'published')' at line 1
Thank you for helping!!
Here is my code:
My Code
The page in question is here:enter link description here
Thanks you very much for helping
The problem was on the line 20--> $query .= "VALUES({$post_category_id}. It need to be quotes around '{$post_category_id}'.
I don't know exactly why. the category id is a number , so for that shouldn't be around quotes because is a number.That's how our teacher explained to as.Thanks for your help.
The $connection variable isn't defined anywhere...
I just populated your page with some example data and that was the query I got:
INSERT INTO posts(post_category_id, post_title, post_author,post_date,post_image,post_content,post_tags,post_status) VALUES(,'','',now(),'',' Test','', 'Test')
The problem is near the VALUES keyword: VALUES (, is wrong. You should check first if every input value is populated correctly, eg if $post_category_id is defined with a valid value.

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 - at line 1

I have this issue here with my code, and cant find where the problem actually is, has anyone had similar issue?
<?php
include("db.php");
if(isset($_POST['submit']))
{
$name=$_POST['namename'];
$job=$_POST['job'];
$message=$_POST['message'];
$insert=mysql_query("insert into commenttable(name,job,message)values('$name','$job','$message')")or die(mysql_error());
header("Location:../home.php");
}
?>
this is running on localhost
Server type: MySQL
Server version: 5.5.42 - Source distribution
forgot to mention that if I post simple comment such a "Hello" it works fine, but when i try to post comment like this
<INPUT TYPE="IMAGE" SRC="javascript:alert('XSS');">
for a attack it wont work and I get the error message.
Im doing this for small attack project, this is why i need to get this to work.
Thanks!
If your code fails when you are trying to insert the text <INPUT TYPE="IMAGE" SRC="javascript:alert('XSS');"> then obviously, what is happening is what Uueerdo suggested in his comment: the single quote right before "XSS" is interpreted by MySQL as the closing single quote of the string, leaving you with a dangling XSS');', which is, of course, a syntax error.
There are two ways to overcome this problem:
Programmatically escape the single quotes. This would be quite tricky if you were to do it by yourself, but there ought to be some library function in PHP for that, so it would look like message = escape_for_sql( message ). (Sorry I am not reproducing the dollar signs, I am allergic.)
Better yet, use a parameterized query, where you construct your query using a "?" in place of each value, signifying a parameter to the query, then you supply the value for each parameter, and then you execute the query. I don't know how this is done in PHP, search for "parameterized query PHP".
To extend #Mike's answer, the correct prepared-statement PHP syntax would be, using the mysql driver:
None. Don't use the mysql driver. It's been deprecated since forever.
Using mysqli:
// You need to define the following $db_* vars elsewhere
$dbh = new mysqli($db_host, $db_user, $db_password, $db_name;)
$query = "INSERT INTO commenttable (name, job, message) VALUES (?, ?, ?)";
$stmt = $dbh->prepare($query);
$stmt->bind_param($name, $job, $message);
$stmt->execute();
// When you're finished...
$stmt->close();
Using PDO:
// Edit the connection string as appropriate for your installation
$dbh = new PDO('mysql:host=mydbhost;dbname=whatever', $db_user, $db_password);
$query = "INSERT INTO commenttable (name, job, message) VALUES (:name, :job, :message)";
$stmt = $dbh->prepare($query);
$params = array(':name' => $name, ':job' => $job, ':message' => $message);
$stmt->execute($params);
// PDO has no explicit close() call.
I leave error handling as an exercise for the reader. Hope that helps.

issues with mysql, specifically the sql function

i'm trying to insert the following code on SQL, however it won't work.
What's the problem :O
Content
$share_text="<img src='http://dosha.re/i/Uvhg.png'/>";
(it's an IMG tag, except stackoverflow won't show the code.)
$sql.=", '$share_text'";
As you can tell, Sharetext does include an img extension but for some reason i get:
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 'http://dosha.re/i/Uvhg.png'/>', 1, '', 'Tue Apr 2 2013', '09:51
PM')' at line 1
You need to call addslashes function around this variable value in which this image tag is coming. It the error of single slashes.
You're using single quotes in the src attribute, but then you wrap the whole thing in single quotes too, so that won't work:
$share_text = '<img src="http://dosha.re/i/Uvhg.png" />';
$sql .= ", '$share_text'";
Alternatively, and probably better, use mysql_real_escape_string() or PDO::quote or mysqli::real_escape_string.
$sql .= sprintf(", '%s'", mysql_real_escape_string($share_text));
It's impossible to tell from this what your real query is, but I would suggest using prepared statements so that you don't have to worry about escaping SQL.

Inserting data using PHP into mysql when it contains a '

I am writing lots of info from an XML file into a database.
Everything works fine until I come across a field with the ' in the description, that insertion fails with an error
Error
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 'd like you to feel that way too.
We'd love to have you visit us to view
over 100' at line 3
Is there a way to have this inserted without it failing? the import file could be large and change regularly so I cannot search and replace ' characters within it.
My actual PHP Statement is:
$query = mysql_query("REPLACE into list
(id, name, link, description, cost, date_added,type,myipaq,private,imgurl)
VALUES ('$id','$name','$link',"'$description'",'$cost','$date','$type','$myipaq','$private','$imgurl')");
thanks in advance,
Greg
This falls under the category of SQL injection.
In PHP a function: mysql_real_escape_string is used to encode a string so that none of it can affect the SQL statement it might be concatenated into.
so make sure all of your values go through the mysql_real_escape_string function and you will be fine.
API REF: http://php.net/manual/en/function.mysql-real-escape-string.php
Just pass your data through mysql_real_escape_string()
Use my handy dandy function:
function mysql_safe_string($value) {
if(is_numeric($value)) return $value;
elseif(empty($value)) return 'NULL';
elseif(is_string($value)) return '\''.mysql_real_escape_string($value).'\'';
elseif(is_array($value)) return implode(',',array_map('mysql_safe_string',$value));
}
function mysql_safe_query($format) {
$args = array_slice(func_get_args(),1);
$args = array_map('mysql_safe_string',$args);
$query = vsprintf($format,$args);
$result = mysql_query($query);
if($result === false) echo '<div class="mysql-error"><strong>Error: </strong>',mysql_error(),'<br/><strong>Query: </strong>',$query,'</div>';
return $result;
}
Like so:
mysql_safe_query('INSERT INTO table VALUES (%s, %s, %s)', $val1, $val2, $val3);
And forget about quoting or not quoting your strings, and writing out mysql_real_escape_string a dozen times.
The only really safe way of inserting or replacing or indeed interacting with anything on a database with PHP is to use prepared statements. There really is no excuse anymore for doing it any other way. Escaping strings using mysql_real_escape_string will give you some protection, but it is not bullet proof.
Prepared statements are not even hard. See the PHP manual page on them, and there are several wrappers to make life even easier, personally I like the codesense mysqli wrapper a lot and have been using it for a while with no problems - it's no harder than straight MySQL PHP code. EasyPDO looks promising too.
You should check out the related question "PHP: Is mysql_real_escape_string" sufficient for cleaning user input" for further details as to why you shouldn't be lazy.
Use: php.net/manual/en/function.addslashes.php
Addslashes prevent's just that!
And if you use that, just use
http://www.php.net/manual/en/function.stripslashes.php
to remove slashes from your string!