I insert a text variable in a mySQL table. Everything works fine except in the text is a quotation mark. I thought that I can prevent an error by using "mysql_real_escape_string". But there is an error anyway.
My insert statement:
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
mysql_real_escape_string($insertimage);
The error message:
MySQL 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 '1413885955514','10')' at line 1
You need to escape data that you are putting into the SQL so that any special characters in it don't break the SQL.
You are escaping all the special characters in the final string of SQL; even those that you want to have special meaning.
If you want to use your current approach, you would do something like this:
$filename = mysql_real_escape_string($filename);
$text = mysql_real_escape_string($text);
$timestamp = mysql_real_escape_string($timestamp);
$countdown = mysql_real_escape_string($countdown);
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
… but the PHP mysql_ extension is obsolete and you shouldn't use it.
Modern APIs, such as mysqli_ and PDO support prepared statements, which are a better way to handle user input. This answer covers that in more detail.
The problem with your current code is that you have not correctly escaped the values you're trying to enter into the table.
Better still is to avoid the mysql_* function family entirely. Those functions are now deprecated and bring security risks to the table (along with other concerns).
You'd be better to use PDO and Prepared Statements, for example:
$db = new PDO('param1', 'param2', 'param3');
$sql = $db->prepare( 'INSERT INTO `image` (`filename`, `text`, `timestamp`, `countdown`)
VALUES (:filename, :text, :timestamp, :countdown)' );
$sql->execute( array(':filename' => $filename,
':text' => $text,
':timestamp' => $timestamp,
':countdown' => $countdown )
);
mysql_real_escape_string($insertimage);
You will have to use this function to each variables before writing the query.
$filename = mysql_real_escape_string($filename);
$text = mysql_real_escape_string($text);
$timestamp = mysql_real_escape_string($timestamp);
$countdown = mysql_real_escape_string($countdown);
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
Try this ,
$insertimage = sprintf("INSERT INTO image(filename,text,timestamp,countdown) VALUES ('%s','%s','%s','%s')", mysql_real_escape_string($filename), mysql_real_escape_string($text), $timestamp, $countdown);
Why, because your inputs vars must be escaped before using them in sql
then execute your sql.
Escaping the entire query is not useful. In fact, right now, you are causing syntax errors by doing so.
You should be escaping the individual variables that you inject into it.
Try this:
$filename = mysql_real_escape_string($filename);
$text = mysql_real_escape_string($text);
$timestamp = mysql_real_escape_string($timestamp);
$countdown = mysql_real_escape_string($countdown);
$insertimage = "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
mysql_query($insertimage);
Concat the php variables like this:
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES (" . $filenamec . "," . $text . ", " . $timestamp . ", " . $countdown . ")";
with the respective single quotes in those that are text fields i.e: "... '" . $text . "' ..."
Related
Here's how my insert code looks:
$values .= ($ta->account_toll_free_number != '') ? ",('" . $post_id . "', 'toll_free_number','" . $ta->account_toll_free_number . "')" : NULL;
Which gives me:
(111, 'toll_free_number', '888-123-1234')
Which works great until there is a single quote mark in the variable. Then it breaks. Is there someway I can clean/escape it before this? Do I just need to swap my single quotes to double quotes?
I did it this way.
I just started with your output and added a single quote for last part.
$values = mysql_real_escape_string("(111, 'toll_free_number', '888-'123-1234')");
$query = "INSERT INTO yourtable (fieldname) values ('".$values."')";
mysql_query($query) or die(mysql_error());
see more from manual http://php.net/manual/en/function.mysql-real-escape-string.php
As the commenter pointed out, I would recommend you use PDO as this is an escaping issue and opens you up to SQL injection vulnerabilities. On the change that you are using mysql_* instead, try escaping the variable with mysql_real_escape_string() first.
Here is a part of my insert code that troubles me:
$recepient="test#email.com";
$text="Please track: http://wwwapps.ups.com/WebTracking/processInputRequest?HTMLVersion=5.0&loc=en_US&Requester=UPSHome&tracknum=123456789&AgreeToTermsAndConditions=yes&ignore=&track.x=24&track.y=9";
$date="2013-05-03 08:12:20";
$through="mail";
$status=1;
$q = "INSERT INTO `messages` (`recepient`,`text`,`date`,`through`,`status`) VALUES('".mysql_real_escape_string($to)."','".mysql_real_escape_string($text)."','".date("Y-m-d H:i:s")."','".mysql_real_escape_string($rowuser['through'])."','".intval($status)."')";
try {$db->query($q);} catch(PDOException $ex) {echp" Error: ".$ex.);}
If I remove the link from the $text variable I can see the data added to the database. But in the way I need it to add with the link - the script stops not reporting any errors.
use PDO's powerful prepared statements:
$q = "INSERT INTO messages (recepient,text,date,through,status) ";
$q .= "VALUES (:to,:text,:date,:through,:status)";
$dbinsert = $db->prepare($q);
$dbinsert->execute(array(
':to' => $recipient,
':text' => $text,
':date' => $date,
':through' => $through,
':status' => $status));
This should do it.
Let PDO take care of escaping.
It would appear that you're mixing database libraries, or have wrapped things yourself.
If you're using something like mysqli or PDO for the ->query() call, then mysql_real_escape_string() will NOT work. m_r_e_s() requires an active connection to the DB to operate. Connections established in mysql, mysqli, and PDO are NOT shareable between the libraries.
That means your m_r_e_s() calls will returning a boolean FALSE for failure, and your query will actually look like:
$q = "INSERT .... VAALUES ('', '', '', etc...)";
What's the size of the text column in the database? It's mostly not the reason but I've noticed that your $text is 190 char long.
The problem is with the "?" sign in the $text variable. It is being treated as a placeholder when it is put into the query, and the $db->query expects an array of variables.
The solution is to use a placeholder instead of a $text variable and submit $text variable as params:
$ar[0]=$text;
$q = "INSERT INTO `messages` (`recepient`,`text`,`date`,`through`,`status`)";
$q.= " VALUES('".$to."',?,'".date("Y-m-d H:i:s")."','".$through."',".$status.")";
$db->query($q,$ar);
I am trying do multi-driver support for my Framework, which basically means I can use MySQL, MySQLi or PDO(MySQL) with ease.
So, let's say I have an array of values I want to insert.
array('Manuel', 'StackOverflow');
and I have this query..
mysql_query("INSERT INTO users(name, fav_site) VALUES(?, ?)");
So, I'd like to replace the question marks with those values in order, so Manuel goes first and then goes StackOverflow. Remembering that I need to add -> ' <- at the sides of these values so MySQL doesn't throw an error.
I have tried searching if someone has asked this and had no luck.
Any help is appreciated!
NOTE: I know I shouldn't even bother with MySQL, but hey! A feature is a feature.
<?php
$query = "INSERT INTO users(name, fav_site) VALUES(?, ?)";
$args = array('joe', 'google goggles');
while(strpos($query, '?') !== FALSE)
{
$query = preg_replace('/\?/', your_quoting_func(array_shift($args)), $query, 1);
}
echo $query;
Basically, this says...while there is still a ? remaining in the string, delete the first question mark and replace it with a quoted (use your own function or mysql_real_escape_string and surround with single quotes) string, and shift that item off the array. You should probably substr_count the ? marks versus the number of arguments for error checking.
I used preg_replace because it accepts an argument specifying how many values to replace, whereas str_replace does not.
I would do it this way (with one exeption: I wouldn't use mysql_):
<?php
$values = array('foo', 'bar');
$query_start = "INSERT INTO `users` (`name`, `fav_site`) VALUES ('";
$query_end = "')";
$query = $query_start . implode("', '", $values) . $query_end;
$result = mysql_query($query);
?>
$query_start contains the start of the MySQL query (notice the ' at the end), and $query_end goes at the end.
Then $values is imploded, with ', ' as the 'glue', and $result is set as:
$query_start (impoded $result) $query_end.
See implode - PHP Manual.
<?php
// This leaves the db connection in $conng require_once('/tms/http/html_docs/tease/csp/csp_tease.php');
/* This a logging function. When called with:
*/
function log_tkt_to_db($tkt_number, $date, $uid, $description, $conng)
{
echo "$tkt_number|$date|$uid|$description<br>";
$sqlinsert = "insert into TEASE_TKTLOGS VALUES ( \"$tkt_number\", \"$date\", \"$description\", \"$uid\")";
echo $sqlinsert . "<br>";
$insert = OCIParse($conng, $sqlinsert);
// OCIExecute($insert, OCI_COMMIT_ON_SUCCESS);
OCIExecute($insert);
}
log_tkt_to_db("00000000", "07/13/2012", "jt898u", "this a test, this is only a test", $conng);
?>
I get this output:
00000000|07/13/2012|jt898u|this a test, this is only a test
insert into TEASE_TKTLOGS (TICKET, DATE_TIME, CHANGE_DESC, ATTUID) VALUES ( "00000000", "07/13/2012", "this a test, this is only a test", "jt898u")
Warning: ociexecute() [function.ociexecute]: ORA-00972: identifier is too long in /appl/tms/http/html_docs/tease/dblog.php on line 17
There are multiple things wrong here.
The simplest answer is that you need to use single quote marks (') instead of double quotes (see String Literals in Oracle Database SQL Reference)
You really should use something like oci_bind_by_name instead of blindly inserting your values into the query. Saves you a parse and a potential SQL injection.
ociparse and ociexecute are deprecated as of PHP 5.4. Instead of these you should use, respectively, oci_parse and oci_execute.
In PHP-script i need to update title, content fields.
If I put "#" into content I get error "Description: Incorrect syntax near '#'."
I fixed with symbols ' ".
Is there any solution for escaping or framework for DB layer?
I'm forced to use f**ng MS SQL :(
Code:
$conn = new COM ("ADODB.Connection")
$db_conn = $conn->open('bla-bla-password...');
$query = sprintf( "UPDATE page SET title='%s', page_content='%s' WHERE id=%d;", addslashes($title), addslashes($content), intval($id));
$rs = $db_conn->execute($query);
Use PDO prepared statements to escape special characters … not sprintf or addslashes.