-2
$sql = "SELECT email FROM family WHERE family = '$family'";
                $result = mysql_query($sqll)or die(mysql_error());

Is this the right way to get php variable into mysql query?

TomTom
  • 1,113
  • 1
  • 10
  • 20

5 Answers5

1

That could work. However, it's vulnerable to SQL injection.

This is safer:

$sql = sprintf("SELECT email FROM family WHERE family = '%s'",
               mysql_real_escape_string($family));
$result = mysql_query($sql);
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
1

If you starting with PHP/MySQL I would recommend you to check PDO or MySQLi extension as it allows you to use more smart database queries and easier to maintain.

Nazariy
  • 6,028
  • 5
  • 37
  • 61
0

The code has a type error

$sqll is not defined.it must be $result = mysql_query($sql).

I believe this is the reason you are looking for...(since the question is too vague which is probably because you got an error that you couldnt track)

rjv
  • 6,058
  • 5
  • 27
  • 49
-1

From my knowledge best way to use like this:

if $family is not string

$sql = "SELECT email FROM family WHERE family = ".$family;

if there is a string comparison then,

$sql = "SELECT email FROM family WHERE family = '".$family."'";
srbhbarot
  • 1,317
  • 12
  • 16
  • Either case is seriously dangerous with out emphasizing sanitizing inputs. Really though the developer shouldn't have to worry about that, just put a ? in it's place and use bound parameters or PDO instead. – atxdba Jan 11 '12 at 05:20
  • @Mischa He is in confusion. He asked what is the right way so from my knowledge i just try to help him nothing else. – srbhbarot Jan 11 '12 at 05:27
  • @srbhbarot Although your intention is good, you're not addressing the problem with the solution. Your code looks vulnerable to SQL injections, which probably is the reason you got downvoted. – Repox Jan 11 '12 at 07:15
-2

'$family' no need of single quotes here

maxjackie
  • 22,386
  • 6
  • 29
  • 37