How to echo if field is not found?

Posted by Fahad on Stack Overflow See other posts from Stack Overflow or by Fahad
Published on 2011-11-18T17:48:51Z Indexed on 2011/11/18 17:50 UTC
Read the original article Hit count: 445

Filed under:
|

Hi I'm trying to figure out how to echo back if the value entered does not match when a database lookup is done.

I'm using ajax to run the request and php to do the lookup

ajax.js:

function showResult(str)
{
if (str=="")
  {
  document.getElementById("description").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("description").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?voucher="+str,true);
xmlhttp.send(null);
}

and getuser.php:

<?php
$q=$_GET["voucher"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test", $con);

$sql="SELECT * FROM redemption WHERE voucher = '".$q."'";

$result = mysql_query($sql);
echo "<table>
<tr>
<th>Name</th>
<th>Product</th>
<th>Address</th>
<th>Status</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['name'] . "</td>";
  echo "<td>" . $row['product'] . "</td>";
  echo "<td>" . $row['address'] ." ".$row['city'] ." ".$row['province'] ." ".$row['postal'] . "</td>";
  echo "<td>" . $row['status'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

What I would like to do is that once the person enters an invalid or a voucher number that is not found I would like to return an error that "Voucher number is not found". There is also a column in the db that stores the status such as "redeemed" or "not redeemed". How could I check for both whether the voucher number exists and if it has already been redeemed?

I assume it'd have to be a syntax such as $sql="SELECT * FROM redemption WHERE voucher = '".$q."'" AND status = 'not redeemed' and then use an else or case statement perhaps?

Thanks in advance

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql