issues with mysql, specifically the sql function - mysql

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.

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.

Multiple Rows INSERT in 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.

SQL syntax in openquery - apostrophes inside query

I have the following issue, I trying to obtain data via linked server in sql server 2008 from BMC Remedy
Everything is fine with connection, but when I added WHERE
"Assigned Group" LIKE '*scri%'*, I get error in sql server because of apostrophes which I have to use because BMC Remedy demands it.
Do you know how to create correct syntax or force sql server to use quotation marks instead of apostrophes, or disable spell checking
SELECT *
FROM OPENQUERY(Remedy,
**'**
SELECT
Incident_Number
FROM
HPD_Help_Desk
WHERE
"Assigned Group" LIKE ' scri% '
**'**
)
When doing SQL queries from within Remedy, I usually create a new field and use workflow to build the SQL query.
Also the syntax of the where clause you specified isn't correct. Try this instead:
SELECT
Incident_Number
FROM
HPD_Help_Desk
WHERE
Assigned_Group LIKE 'scri%'
There maybe a white spaces that cause you a problems.
You can also try this one:
SELECT Incident_Number
FROM HPD_Help_Desk
WHERE Assigned_Group LIKE '%scri%'
Or you can try to run this one if you run sql on DB:
SELECT r.Incident_Number
FROM ARADMIN.HPD_Help_Desk as r
WHERE r.Assigned_Group LIKE '%scri%'
Because you're running OPENQUERY, maybe double apostrophes will be needed or double quotes instead of one quote (" intead of ').
Good Luck

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!