Question

I have a PHP statment that $_GET's input from a html page and uses that input(customerID) to search through the database for appropriate results. I have that working fine. What i want to do is, if the user enters an invalid customerID, i want the system to give a message and terminate, else if the user input is correct, i want it to be business as usual.

$id = $_GET['customerID'];
$conn = mysql_connect("localhost", "user", "password"); 
mysql_select_db("databse", $conn) 
or die ('Database not found ' . mysql_error() ); 
$sql = "SELECT .......
        WHERE order.customerID = $id
        ORDER BY order.orderDate ASC";

if($id != 'order.customerID'){
die('Invalid Customer ID entered');}
else
{   
    $rs = mysql_query($sql, $conn) 
     or die ('Problem with query' . mysql_error()); 
}  

Thats my php code. When i run that, if i enter a invalid ID, it will show me 'Invalid Customer ID entered' but when i enter a vaild customerID, it still shows me that error message. Obviously im making a mistake which im not seeing, any help would be appreciated.

Was it helpful?

Solution

First, never trust data from the user, so patch this:

$id = $_GET['customerID'];

With

$id = mysql_real_escape_string($_GET['customerID']);

It sanitizes your value (although it's not completely safe).

For your main problem,

if($id != 'order.customerID'){

order.customerID is just a string. The correct way to check would be to execute the query first, then check if any rows have returned using mysql_num_rows(), if not display an error message else carry on.

$rs = mysql_query($sql, $conn)  or die ('Problem with query' . mysql_error());
if($rs && mysql_num_rows($rs)>0){ 
  //query success and rows returned
}
else
{
  die('Invalid Customer ID entered');
}

Note:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

OTHER TIPS

You need to change your logic a bit. First, you need to check if the customerID exists (probably in a "customers" table?) and then proceed with your query.

For example:

$customerID = mysql_real_escape_string( $_GET['customerID'] ); //fixes sql injection 

$queryString = "SELECT * FROM customers WHERE customerID = {$customerID} LIMIT 1";

$query = mysql_query( $queryString ) or die( mysql_error() );

if (mysql_num_rows( $query ) == 0) {
    die( 'Invalid Customer ID entered' );
}

// from here onward you may proceed with your previous statement.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top