0

I am facing some problem with fetching data from SQL.

When I use the below statement, it is working fine

$sql = 'SELECT `Name`, `Des`, `Url`, `about`, `date` FROM `data` where name = \'facebook\''; 
$retval = mysql_query( $sql, $conn );

When I use the same using a parameter name, I am facing some problem, the code I used is

$name = $_GET['name'];
$sql = 'SELECT `Name`, `Des`, `Url`, `about`, `date` FROM `data` where name = \'$name''; 
$retval = mysql_query( $sql, $conn );

I also tried by concatenating name like \'facebook\'

$name1 = "\'".$name . " \'";  but it is also not working .
John Woo
  • 258,903
  • 69
  • 498
  • 492

2 Answers2

3

use Double quotes so you won't need any escaping of single quotes.

$sql = "SELECT  Name, Des, Url, about, date
        FROM    data 
        where   name = '$name'";

As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
0

Use Mysqli instead of Mysql.

Solution for your query :

$name = $_GET['name']; 
$sql = "SELECT Name, Des, Url, about, date FROM data where name = '".mysql_real_escape_string($name)."'";
$retval = mysql_query( $sql, $conn );
Suhel Meman
  • 3,702
  • 1
  • 18
  • 26