I am writing a query to search a database and print out the resulting customer numbers. I've been trying to add in error checking so that if a number is entered and not in the database it prints out a message. Is there any way to have php ignore the input field the first time around so that I do not have to have the message pop up once the web page is loaded?
<html>
<head>
<title>Select Customer Listing</title>
</head>
<?php
session_start();
echo "Hello, " .$_SESSION['username'];
//Address error handling
ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);
//Define the Customer Number php variable name
$customer = $_POST['cusnum'];
print "<br>The customer number chosen is <strong>$customer</strong>.<br />";
//Attempt to connect
if($connection = @mysql_connect('localhost', 'username', 'password')){
print '<p>Successfully connected to MySQL.</p>';
}
else{
die('<p>Could not connect to MySQL because: <b>' .mysql_error().'</b></p>');
}
if(@mysql_select_db("GIULIANA_PREMIERE", $connection)){
print '<p>The <i>GIULIANA_PREMIERE</i> database has been selected.</p><hr>';
}
else{
die('<p>Could not select the GIULIANA_PREMIERE database because: <b.' .mysql_error().'</b></p>');
}
?>
<?php
//define query
$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_NUM = '$customer'";
$queryALL = "SELECT * FROM CUSTOMER";
$lower = strtolower($customer);
//output the resulting query table
if($r = mysql_query($query)){
while($row = mysql_fetch_array($r)){
print "<p><b>{$row['CUSTOMER_NUM']}</b> : {$row['CUSTOMER_NAME']}<BR/> </P>
";
}
}
//if any case of 'all' is entered, print out query
if(strcmp($lower, 'all') == 0){
if($r2 = mysql_query($queryALL)){
while($row2 = mysql_fetch_array($r2)){
print "<p><b>{$row2['CUSTOMER_NUM']}</b> : {$row2['CUSTOMER_NAME']} <BR/></P>
";
}
}
}
//if no number was entered, display pop up
if(empty($customer) && counter != 1){
print '<script language="javascript">';
print 'alert("Please enter a customer number.")';
print '</script>';
}
//if entered number was invalid, display message
if((mysql_num_rows($r) == 0) && (strcmp($lower, 'all') != 0)){
print "Not a valid cutomer number.";
print "<br>Please try again.";
}
?>
</body>
</html>
I've tried changing all of the if
statements to elseif
but I can't get that to work, either.
Try this:
<html>
<head>
<title>Select Customer Listing</title>
<script>
<?php
$counter = 0; //any number but one
if(empty($customer) && $counter != 1){
$counter = 1; //the condition has been met, lets change the variable to 1 so this condition isn't met again
?>
alert("Please enter a customer number.");
<?php
}
?>
</script>
</head>
//rest of your code