Hi there hopefully someone can help,
On one page I have a form where you enter an id number, on form submission if the id number is in the database it shows info from the database if not it should show no. Please see the code below, at the moment if you enter an id number that is in the database it works correctly and shows the database info, however if you enter a number that is not in the database it does not show anything and I want it to echo no.
I would be really grateful if someone could point me in the right direction.
include '../book_classified_advertising/dbc.php';
$deletepost = $_POST['webid1'];
$result = mysql_query("SELECT * FROM class WHERE webid='$deletepost'");
while($row = mysql_fetch_array($result))
{
if ($deletepost == $row['webid'])
{
echo $row['text'];
}
else
{
echo 'no';
}
}
because the $deletepost
you are using in where its same in if so the condition in if will true always if there is any row with the $deletepost
you can check this by mysql_num_rows($result)
its like
$$deletepost =2'
query
$result = mysql_query("SELECT * FROM class WHERE webid='2'");
and
$row['webid'] will be 2
if ($deletepost == $row['webid']) ///its like if(2 == 2)
{
echo $row['text'];
}
try something like
$result = mysql_query("SELECT * FROM class WHERE webid='$deletepost'");
if(mysql_num_rows($result)){
while($row = mysql_fetch_array($result))
{
echo $row['text'];
}}else
{
echo 'no';
}
The problem is here:
while($row = mysql_fetch_array($result))
If there is no results then your if statement will never run.
First of all, your code is vulnerable to the most basic form of SQL Injection (unless some form of sanitization is applied in the file you are including at the beginning of your script).
Now, as per your problem, the else
part of that condition is never reached, because it's nested inside the iteration through all the results from the database query. If there are no results, no statement within the while
loop gets executed.
You need to reorganize your code for that:
$result = mysql_query("SELECT * FROM class WHERE webid='$deletepost'");
if( mysql_num_rows($result) == 0) {
echo 'no';
}
else {
while($row = mysql_fetch_array($result)) {
echo $row['text'];
}
}
Use Mysql_num_rows to check no of record
$num_rows = mysql_num_rows($result);
if($num_rows)
{
True condition
}
else
{
Fales condition
}