0

I have tried everything I can think of to get query to recognize the WHERE clause.

$sn equals H-001 and sn is the column name

Here is the query:

$result = mysql_query("SELECT * FROM `insp` WHERE sn = $sn") or die(mysql_error());   

I can get everything off the table if I don't use the WHERE clause. I can get the result if I make $sn a straight number with no letters of hyphen. I think I need something for the WHERE to recognize H-001 as a string.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141

2 Answers2

0

The string must be contained within quotes.

So, the sql you need looks like: "SELECT * FROM insp WHERE sn = 'H-001'"

Try this:

$sn = "H-001";
$sql = "SELECT * FROM insp WHERE sn = '" . $sn . "'";
$result = mysql_query($sql) or die(mysql_error());
Rob MacMillian
  • 576
  • 4
  • 14
  • Damn!! I'm 3 seconds too late :P – Mohd Abdul Mujib Jun 28 '15 at 23:01
  • thanks guys. I have tried that also. What i have been able to figure out so far is that if i go to MySQLAdmin and manually enter the $sn then the query works. or if i write out $sn = "H-001" then insert it into the database the query works. But when I get $sn passed from a form and insert it into the database the query does not work. I can look at the database and see the entries but the only ones i can pull down are the ones that i hard coded. – Bryan Combs Jun 29 '15 at 23:55
  • Thanks for the help guys. I found that by passing the variable from page to page that a space was being added to the variable. I used: $sn=preg_replace('/\s+/', '', $sn); and var_dump($sn); to strip the space and to check what was being posed. Wow 5 full days trying to find this. Thanks to everybody who answered. – Bryan Combs Jun 30 '15 at 01:02
0

You should enclose your variable in inverted commas.

Which makes the code as

$result = mysql_query('SELECT * FROM `insp` WHERE `sn` = "'.$sn.'"') or die(mysql_error());

Also please start using the new Mysqli functions or the PDO, as soon as possible.

Since the mysql native functions are deprecated and pretty unsecure.

Update:- Since you mention the form input, maybe try typecasting the value as shown below.

//suppose the value is coming from $_POST['srno'];

$sn = (string) $_POST['srno'];

.....
Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
  • Thanks I've tried this format also with no luck. It only works with hard coded variable. HMMM not sure. I've tried to change the variable $sn to a string and see if the query would recognize that but it only works if i write it out as $sn="H-001" it i pass it to the database from a form it doesn't work. – Bryan Combs Jun 29 '15 at 23:59
  • @BryanCombs I just introduced (updated my answer) a few backquote and reversed the inverted commas, should work IMHO. – Mohd Abdul Mujib Jun 30 '15 at 00:22