PDA

View Full Version : Beginner's PHP issue - what's wrong with my code?


chornbeck
02-02-2006, 04:52 PM
OK, here's the deal. Have an HTML form that asks for a person's last name. It then must query my MySQL DB and return all 4 fields for each record that matches the last name that was entered (some last names have up to 10-11 records).

Here is my form:
<form method="POST" action="lookup.php">

Last Name:<br><br>

<input type="text" name="LstName" value=""><br><br>


<input type="submit" name="submit" value="submit"></form>

And here is the PHP process..

<?
if($_POST['submit']){


mysql_connect ("localhost","orlandoi_referra","referral2");
mysql_select_db ("orlandoi_referralowners") or die ('I cannot connect to the

database because: ' . mysql_error());;



$LstName=$_POST['LstName'];

$result = mysql_query("SELECT * FROM owner_data WHERE LastName=$LstName")
or die(mysql_error());

$row = mysql_fetch_array($result);
// Print out the contents of the entry
echo "First: ".$row['FirstName'];
echo "Last: ".$row['LastName'];
echo "ZIP: ".$row['PostalCode'];
echo "OwnerID: ".$row['OwnerID'];


}

?>

I keep getting this error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/orlandoi/public_html/referral/lookup.php on line 15

Also, my knowledge is very limited, but I believe I need to set up some kind of loop to display all pertinent records (which I don't know how to do).

If anyone can point me in the right direction, it would be greatly appreciated!

chornbeck
02-02-2006, 04:56 PM
I'm also receiving this error: (when I input the name Johnson for instance..)

Unknown column 'Johnson' in where clause

TheShaner
02-02-2006, 05:05 PM
I inserted comments to tell you what I changed.
<?
if($_POST['submit'])
{
mysql_connect("localhost","orlandoi_referra","referral2");
mysql_select_db("orlandoi_referralowners") or die ('I cannot connect to the database because: ' . mysql_error()); // You had two semi-colons here

$LstName = make_safe($_POST['LstName']); // function is below to make it safe for DBs

$result = mysql_query("SELECT * FROM owner_data WHERE LastName = '$LstName'") or die(mysql_error()); // Needed single quotes around variable

// Need loop to pull all records returned by query
while($row = mysql_fetch_array($result))
{
echo "First: ".$row['FirstName'];
echo "Last: ".$row['LastName'];
echo "ZIP: ".$row['PostalCode'];
echo "OwnerID: ".$row['OwnerID'];
}
}

// This function makes a variable safe for inserting into a DB (prevents stuff like SQL injections
function make_safe($variable)
{
$variable = addslashes(trim($variable));
return $variable;
}
?>
-Shane