Page 1 of 1
ERROR BUT WHY? while($row = mysql_fetch_array($q))
Posted: Sat May 15, 2010 2:24 pm
by tom8521
I am getting an error but am unsure why this is.
Top of my page has this information:
$Prop_beds = $_POST['Prop_beds'];
$Prop_type = $_POST['Prop_type'];
$Prop_location = $_POST['Prop_location'];
$q = "SELECT * FROM property WHERE Prop_beds = '$Prop_beds' AND Prop_type = '$Prop_type' AND Prop_location = '$Prop_location'";
Then further down is this bit which causes the error (or so i am told)
while($row = mysql_fetch_array($q))
What am I doing wrong?
Re: ERROR BUT WHY? while($row = mysql_fetch_array($q))
Posted: Sat May 15, 2010 4:36 pm
by collette
It seems you are not testing if the $_POST variables contain anything. I always use:
Code: Select all
$Prop_beds = isset($_POST['Prop_beds']) ? $_POST['Prop_beds'] : null;
$Prop_type = isset($_POST['Prop_type']) ? $_POST['Prop_type'] : null;
$Prop_location = isset($_POST['Prop_location']) ? $_POST['Prop_location'] : null;
and before preparing the query test to see if any is null. Instead of using null you could also use a default value for those variables.
If you write your query like this:
Code: Select all
$q = "SELECT * FROM property WHERE Prop_beds = '".$Prop_beds."' AND Prop_type = '".$Prop_type."' AND Prop_location = '".$Prop_location."'";
it might work. Have seen situations where your line of code does work and have seen it fail (maybe it depends on the php installation, don't know).
I assume you have an { behind the while(....). and that the connection to the database is open.
Other than that, I don't see why you are getting an error.
Re: ERROR BUT WHY? while($row = mysql_fetch_array($q))
Posted: Sat May 15, 2010 8:08 pm
by requinix
And the other two obvious things to say:
1.
mysql_real_escape_string
2. What error?
Re: ERROR BUT WHY? while($row = mysql_fetch_array($q))
Posted: Sat May 15, 2010 8:21 pm
by JakeJ
First of all... what Tom said about making sure your $_POST data is actually there.
There is a glaring deficiency though. You're not actually executing the query in $q. You've just declared a string.
Code: Select all
//so you can do this:
$q = mysql_query("SELECT * FROM property WHERE Prop_beds = '$Prop_beds' AND Prop_type = '$Prop_type' AND Prop_location = '$Prop_location'");
While ($row = mysql_fetch_array($q)) {
//do something.
}
//or try this
$q = "SELECT * FROM property WHERE Prop_beds = '$Prop_beds' AND Prop_type = '$Prop_type' AND Prop_location = '$Prop_location'";
$qry = mysql_query($q);
While ($row = mysql_fetch_array($qry) {
//do something
}
Another thing I'd add is that if you're SURE you'll only get one result, use mysql_fetch_assoc() instead of mysql_fetch _array()
And if you ARE only returning one row, then you don't need the loop.
Code: Select all
$row = mysql_fetch_assoc($q): //assuming my earlier fix for adding mysq_query() to $q
echo $row['Prop_beds'].'<br>';
echo $row['Prop_type'].'<br>';