ELSE condition is not working in the while loop in PHP - php

<?php
$conn=mysqli_connect("localhost","id6755695_artemi8","sharanod"
,"id6755695_user_info");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$department = $_POST["department"];
$year = $_POST["year"];
$sem = $_POST["semester"];
$reg = $_POST["regulation"];
$sql = "SELECT book_name, author, edition, image FROM dept_search WHERE
department='$department' AND year='$year' AND semester='$sem' AND
regulations='$reg' ";
$result=mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result))
{
if($row)
{
echo "<br>";
?>
<img src=" <?php echo $row['image']; ?> " height="300" width="300">
<?php
echo "<br>";
echo "<b>",$row['book_name'],"</b>";
echo "<br>";
echo $row['author'];
echo "<br>";
echo $row['edition'];
}
else
{
echo "sorry book not found";
}
}
mysqli_close($conn);
?>
please help me with this code,i am building a library management system.. The thing is I should be able to display the books if the given values are present i have in the database if not book not found must be displayed but in while loop after if, else does not runs.....

As others have pointed out, your else statement will never run. If you are already inside the while loop, you will certainly have $row defined and for that reason, else will never run.
What you can do is, check beforehand if the query returned actual results, like so:
$result=mysqli_query($conn,$sql);
if($result->num_rows > 0){
while($row = mysqli_fetch_assoc($result)){
echo "<br>";
?>
<img src=" <?php echo $row['image']; ?> " height="300" width="300">
<?php
echo "<br>";
echo "<b>",$row['book_name'],"</b>";
echo "<br>";
echo $row['author'];
echo "<br>";
echo $row['edition'];
}
}else{
echo "Sorry book not found";
}

You can try with mysqli_num_rows .. sample code as follows :
$rowcount=mysqli_num_rows($conn,$sql);
if($rowcount!=0){
$result=mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result))
{
echo "<br>";
?>

You are looping through all the rows returned from the "mysqli_fetch..." command. Your "if" and "else" is useless -- you will always have rows. If you get no rows, you do not even enter the body of the while loop.
You need to COUNT the rows returned (count($row)) and display a message that nothing was found if the count is less than one.

All you need to do is that you have to change if the condition from if($row) to if($other_condition)
Currently, you are just checking either there is something inside $row, and this condition will never be wrong unless you will assign it null. Because where $row will have something then while loop will be executed, and when while loop will be executed then if condition will be executed.
you have to simply one thing, that is to change if condition like given below...
if($row['value'] == 'something')

Related

Panel List Php not showing all data

I am trying to create a panel list that shows certain rows from my database, however when I'm trying to call it, it only shows 1 data in the row even though i limit it by 5.
Here is my script:
<?php
$link = mysqli_connect("localhost", "root", "", "test");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM updates order by id desc limit 5";
if($result = mysqli_query($link, $sql)){
if($list=mysqli_fetch_array($result)){
echo "<div class=\"container\">";
echo "<table>";
echo "<tr>";
echo "</tr>";
echo "<div class=\"col-md-4\">";
echo "<div class=\"panel panel-primary\">";
echo "<div class=\"panel-heading\">Updates";
echo "</div>";
echo "<ul class=\"list-group\">";
echo "<li class=\"list-group-item\">";
echo "<b><h4>{$list["updates"]}</b></h4>";
echo "</li>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
}
echo "</table>";
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
That's because you are fetching only once, here:
if ($list=mysqli_fetch_array($result) )
Instead wrap this up inside a loop like this:
$row_count = mysqli_num_rows($result);
if ($row_count <= 0) {
echo "No records matching your query were found.";
}
else {
// you have results
// panel starts here
while ($list = mysqli_fetch_array($result)) {
// do some magic with your results
}
// panel ends here
mysqli_free_result($result);
}
I think you got the idea, now you can do the rest. If not let us know again. Happy coding!
You use sql to get five data, but you use mysqli_fetch_array() function only took out a line.
error line 8;

PHP: While loop does not run when the condition is true

The following PHP program is to search for a student number in database and display the details if found or give a message if it does not exist.
<html>
<body>
<?php
$sno=$_POST['studNo'];
$connection = mysql_connect("localhost", "root", "")
or die("couldn't connect to the server");
$db = mysql_select_db("student", $connection)
or die("<b>connection fails");
$query = "select * from performance where Number = '$sno'";
if($result = mysql_query($query))
{
echo "<table border = 1 align = center>";
echo "<tr>";
echo "<th>Number<th>Name<th>Address<th>Mobile Number";
echo "</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<th>",$row['Number'],"</th>";
echo "<th>",$row['Name'],"</th>";
echo "<th>",$row['Address'],"</th>";
echo "<th>",$row['MobileNo'],"</th>";
echo "</tr>";
}
echo "</table>";
echo "The student data updated";
}
else
{
echo "<b>Customer number does not exist";
}
mysql_close($connection);
?>
</body>
</html>
If i search for a number which does not exist the else block runs. When i give a number which exists then the if block runs but the while loop does not run. Can anybody help me out? Database field names are correct.
mysql_query() only returns false if there's an error in the query. Not finding any matching rows is not an error. To tell if any rows were found use mysql_num_rows().
$result = mysql_query($query) or die("Query error: " . mysql_error());
if (mysql_num_rows($result) > 0) {
...
} else {
echo "<b>Customer number does not exist</b>";
}

while mysql_fetch_array loop doesn't run

Here is my code
$itemSelect="select * from items where gender='men' and type='suite'";
$itemQuery=mysql_query($itemSelect) or die(mysql_error());
$num=count($itemQuery);
echo $num;
if($itemQuery)
{
echo "I am here";
echo "<table>";
while($row = mysql_fetch_array($itemQuery))
{
$photo=$row['photo'];
$name=$row['name'];
$price=$row['price'];
echo "<tr><td>". $photo ."</td><td>" .$name ."</td><td>" .$price ."</td> </tr>";
}
echo "</table>";
}
else
{
echo "There is some mistacke";
die();
}
So here $num=count($itemQuery); shows me that there is 1 item that satisfies the search but the loop is never executed what could be the problem? Thanks in advance.
The reason you are getting 1 is because of this code:
$num=count($itemQuery);
echo $num;
count is a function to get the number of items in an array. If you pass anything that isn't an array (or doesn't implement the ICountable interface), then count returns always 1.
So this piece of code is incorrect in that it shows 1, while that number isn't at all related to the number of rows returned.
The query itself looks fine to me, although I cannot validate it against your actual database. If you see the message "I am here", then your query executed fine, but didn't return any rows. If you don't see that message, then something else went wrong. You can use mysql_error to try to find any errors in that case.
$count= mysql_num_rows($itemQuery);
echo $count;
if($count > 0)){
echo "<table>";
while($row = mysql_fetch_array($itemQuery)){
$photo=$row['photo'];
$name=$row['name'];
$price=$row['price'];
echo "<tr><td>". $photo ."</td><td>" .$name ."</td><td>" .$price ."</td> </tr>";
}
echo "</table>";
}else{
echo "there are no results";
die();
}

Added if else argument and lost variable from database

<?php
$con=mysqli_connect("localhost","root","","clarks");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$place = $_GET['place'];
$place2 = $_GET['place2'];
$return = $_GET['return'];
$people = $_GET['people'];
$pickup = $_GET['pickup'];
$dropoff = $_GET['dropoff'];
$result = mysqli_query($con,"SELECT * FROM pricelist WHERE place1='$place' AND place2='$place2' AND people='$people'");
while($row = mysqli_fetch_array($result))
{
if (!empty($row['Price']))
{
echo "Not Applicable";
}
else
{
echo "<html><body style='background-color: #31ff01;'><link rel='stylesheet' href='css/bootstrap.min.css'>";
echo "<div id='prices'>£";
echo $row['Price'] * $return + $pickup + $dropoff;
echo "</div>";
echo "<div id='back'>";
echo "<a href='index.html'>Go Back</a>";
echo "</div>";
echo "<br>";
}
}
mysqli_close($con);
?>
This is returning the "Not Applicable" from the if argument every time.
I've tried placing the lines in different order and using both the price and result variable, it still only returns not applicable but without the if else argument, the rest of it works as intended and brings up a price so I know the price variable shouldn't be empty and neither should the result variable.
With it returning not applicable all the time, I assume it's not retrieving the information from the database properly any more but I can't figure out why when it works perfectly fine without the if else.
Any help would be great, Thanks.
Your logic is wrong:
if (!empty($row['Price']))
^ here
{
echo "Not Applicable";
}
should be:
if (empty($row['Price']))
{
echo "Not Applicable";
}
You also have a serious sql injection problem, you should use prepared statements or at the very least use mysqli's escaping function.
if (empty($row['Price']))
{
echo "Not Applicable";
}
else
{
echo "<html><body style='background-color: #31ff01;'><link rel='stylesheet'
.....
}
}
I think the in the if condition the negation causes the problem
Remove the exclamation mark!
It might be because you are using mysqli_fetch_array instead of mysqli_fetch_assoc. http://www.php.net/manual/en/mysqli-result.fetch-assoc.php
You should also start using real_ escape_ string on your parameters, or do it in the right way with parameterized prepared statement. http://www.php.net/manual/en/mysqli.prepare.php
<?php
$con=mysqli_connect("localhost","root","","clarks");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$place = $_GET['place'];
$place2 = $_GET['place2'];
$return = $_GET['return'];
$people = $_GET['people'];
$pickup = $_GET['pickup'];
$dropoff = $_GET['dropoff'];
$result = mysqli_query($con,"SELECT * FROM pricelist WHERE place1='$place' AND place2='$place2' AND people='$people'");
$row = (mysqli_fetch_array($result));
$a = $row[3];
if (empty($a))
{
echo "<html><body style='background-color: #31ff01;'><link rel='stylesheet' href='css/bootstrap.min.css'>";
echo "<div id='prices'>";
echo "N/A";
echo "</div>";
echo "<div id='back'>";
echo "<a href='index.html'>Go Back</a>";
echo "</div>";
echo "<br>";
}
else
{
echo "<html><body style='background-color: #31ff01;'><link rel='stylesheet' href='css/bootstrap.min.css'>";
echo "<div id='prices'>£";
echo $a * $return + $pickup + $dropoff;
echo "</div>";
echo "<div id='back'>";
echo "<a href='index.html'>Go Back</a>";
echo "</div>";
echo "<br>";
}
mysqli_close($con);
?>
Well I found this workaround, instead of using while I just got rid of it and assigned the price from the database into its own variable meaning there's no conflict with the if else statement. Works like a charm... now to look at prepared statements :S

SQL Not Found Condition

I have a php script that tries to find a particular name in a database where the specified program is $q, a variable passed from an html page. I'm very new to this so I'm having trouble figuring out how to code an if not found, then display type of message. Below is what I currently have:
$sql="SELECT * FROM names WHERE program='".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<div class='header'>Program Name:</div>";
echo "<div class='data'>";
echo $row['program'];
echo "</div>";
}
And I need it to echo a message saying if nothing was found. I tried looking at NOT IN condition in SQL and http://www.techonthenet.com/sql/exists.php along with other things on the internet but I'm not sure if this is the right thing to use. Any help would be appreciated.
use th php function
mysql_num_rows($result);
to check results found
So your code should be like:
$sql="SELECT * FROM names WHERE program='".addslashes($q)."'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
while($row = mysql_fetch_array($result))
{
echo "<div class='header'>Program Name:</div>";
echo "<div class='data'>";
echo $row['program'];
echo "</div>";
}
else
echo "No data found";
please note i added
addslashes($q)
in query, in order to avoid SQL injection problems.
$sql="SELECT * FROM names WHERE program='".$q."'";
$result = mysql_query($sql);
$found = false;
while($row = mysql_fetch_array($result))
{
$found = true;
echo "<div class='header'>Program Name:</div>";
echo "<div class='data'>";
echo $row['program'];
echo "</div>";
}
if ($found == false)
echo "I found nothing";

Categories