0

I have a PHP script that is for direct calling that checks to see if a key is in the blacklist database. However, no matter what I try, including mysql_num_rows, it always returns that the value does not exist (returns 'OK')...

What am I doing wrong?

<?php

$pin = $_GET['keycode'];

$cn=mysqli_connect('localhost', 'root', 'password', 'serials') or die($cn->connect_error);
$sql = "SELECT keycode FROM blacklist";
$rs = $cn->query($sql) or die(mysqli_error($cn));
while($row = mysqli_fetch_array($rs)){
if ($row[keycode] == $pin) {
    echo "BL";
    return;
}
}
echo "OK";
$cn->close(); 
?>
Chris
  • 149
  • 12

1 Answers1

3

Change your code to this :

<?php  
  $cn = mysqli_connect('localhost', 'root', 'password', 'serials');

  $pin =  $_GET['keycode'];

  $sql = $cn->prepare("SELECT * FROM blacklist WHERE keycode = ?;");

  $sql->bind_param('s', $pin);// set $pin to type string and bind it to the query

  $sql->execute();// execute query

  $result = $sql->get_result();// get the result

  if(mysqli_num_rows($result)>0){
     echo "Keycode Blacklisted";// inform that keycode found in blacklist
  }

  $cn->close(); 
?>

The problem with your code is :

  1. You have not added single quotes to your $row[keycode] so change it to $row['keycode']
  2. Your query was not selecting all columns but still you were treating the result as if it had several rows when you were using $row['acolumn']. Plus you were not using your $pin to check for equality first. By using SELECT * FROM blacklist WHERE keycode = ?; you will check for equality without needing the if condition. So that's the explanation for my code change.
Dharman
  • 30,962
  • 25
  • 85
  • 135
programmingandroid
  • 340
  • 1
  • 5
  • 14