Reputation: 649
I want to execute a mysql query from php.
$sql = insert into q_links values ( 'garment.png', 'imgs\ques\p1\garment.png' );
I couldn't store the url as it is, rather it is being stored like this: imgsquesp1garment.png
. But I want to store the url like: imgs\ques\p1\garment.png
. So I tried this:
$sql = mysql_real_escape_string($sql);
But this way my $sql
looks like:
insert into q_links values ( \'garment.png\', \'imgs\\ques\\p1\\garment.png\' );
which do not work in the mysql database.
I have to insert this url in the database for later use. The url is imgs\ques\p1\garment.png
. How can I achieve this?
Update: And I tried with the first comment which worked for me.
So the solution is:
$sql = "insert into q_links values ( 'garment.png', '".mysql_real_escape_string( 'imgs\ques\p1\garment.png' )."' );";
Upvotes: 6
Views: 6771
Reputation: 8020
Add the escape only for img field:
$sql = "insert into q_links values ( 'garment.png', '".mysql_real_escape_string( 'imgs\ques\p1\garment.png' )."' );"
Upvotes: 2
Reputation: 547
You can use this code to enter image url in database
$url =mysql_real_escape_string('imgs\ques\p1\garment.png');
$sql = "insert into q_links values ( 'garment.png', '".$url."' );
if you execute the query: insert into q_links values ( 'garment.png', 'imgs\ques\p1\garment.png' );
it will insert successfully in database
Upvotes: 1
Reputation: 123
I can be like this:
$img=addslashes("imgs\ques\p1\garment.png");
$sql=insert into q_links values('garment.png',$img);
and while retriving you can use stripslashe();
Upvotes: 1
Reputation: 5399
Use PDO. mysql_
is deprecated anyway.
$params = array('value_one','value_two')
$dbh = new PDO('credentials go here');
$sql = 'insert into q_links values ( ?, ? );';
$stmt = $dbh->prepare($sql);
$stmt->execute($params);
Using PDO you would prepare your statement and then call execute it with the exacte variable you want. It would escape it all for you.
Upvotes: 0
Reputation: 17013
$url = "imgs\ques\p1\garment.png";
$url = mysql_real_escape_string($url);
$sql = "INSERT INTO q_links VALUES ('garment.png', '$url')";
As a side note, the mysql_* functions are deprecated, and you should move to Prepared statements with mysqli_* or PDO.
Example in PDO:
$pdo = new PDO("mysql:host=localhost;port=3306;dbname=mydb", "user", "password");
$stmt = $pdo->prepare("INSERT INTO q_links VALUES (?, ?)");
$stmt->execute(array("garment.png", "imgs\ques\p1\garment.png"));
$stmt->closeCursor();
Upvotes: 4
Reputation: 16989
Why don't you store it with forward slashes as such?
$sql = insert into q_links values ( 'garment.png', 'imgs/ques/p1/garment.png' );
Upvotes: 2
Reputation: 263723
don't escape the single quote, only the \
$var = "insert into q_links values ( 'garment.png', 'imgs\\ques\\p1\\garment.png');"
Upvotes: 2