Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store URL in mysql

Tags:

php

mysql

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' )."' );";
like image 347
Cool Brain Avatar asked Jan 31 '13 13:01

Cool Brain


People also ask

How do you store links in a database?

You shouldn't have to do anything special to store a hyperlink within your database as they are simply strings. So you'll want to use a VARCHAR or TEXT field and you may want to consider making it fairly large (ie VARCHAR(512) or VARCHAR(MAX)) as URLS "can" be quite large although you may not run into any that big.

What is the datatype for URL in MySQL?

The datatype for the URL is VARCHAR.

What is the datatype for URL?

URL is a built-in datatype of Semantic MediaWiki that is used for the most common kinds of URLs, URNs, and URIs. It accepts almost any string and interprets it as a URL. The URL appears as a link in text and the Factbox. Technically speaking, e-mail addresses and even telephone numbers are also kinds of URLs.


2 Answers

$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();
like image 78
crush Avatar answered Sep 19 '22 12:09

crush


Add the escape only for img field:

$sql = "insert into q_links values ( 'garment.png', '".mysql_real_escape_string( 'imgs\ques\p1\garment.png' )."' );"
like image 31
Peon Avatar answered Sep 19 '22 12:09

Peon