Panel List Php not showing all data - php

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;

Related

ELSE condition is not working in the while loop in 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')

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>";
}

For loop retrieves same mysql row

I’m trying to retrieve the first 4 entries with a for loop, but it seems to repeat 1 entry 4 times.
This is my code:
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten");
while($row = mysqli_fetch_array($result)) {
for ($result = 1; $result <= 4; $result++) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
}
mysqli_close($con);
You don't need a for loop. I've modified code, to retrive only first 4 items.
Look at the cahnged query LIMIT 4.
<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten LIMIT 4");
while($row = mysqli_fetch_array($result)) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
mysqli_close($con);
?>
You have a for loop inside the while loop. You can remove the for loop and use LIMIT from MySQL (which is better as fetching all entries by PHP (better performance), if you need only the first 4 entries):
SELECT * FROM activiteiten LIMIT 4
If you still want to do it with php:
$results = 0;
while($row = mysqli_fetch_array($result) && $results < 4) {
echo "<div class='agenda_item' style='background-color:#F39'>";
...
$results++;
}
Your code—as presented—mixes things up in ways that behave the way you see. The for loop is not needed. And you should set a LIMIT in your MySQL query like this:
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten LIMIT 0,4");
while($row = mysqli_fetch_array($result)) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
mysqli_close($con);
The problem with your original code is mixing for with while ends up in the scenario you showed as explained in the PHP manual entry for while:
The meaning of a while statement is simple. It tells PHP to execute
the nested statement(s) repeatedly, as long as the while expression
evaluates to TRUE.
So you have a while iterating over the results, but then you also have for loop nested in there. 100% unnecessary.
The way I adjusted it is to just removed that for loop, but also add LIMIT 0,4 to the MySQL query. That basically tells MySQL to fetch 4 rows beginning from the first row which is referred to as 0.

Only Displaying one row Mysql

I want this data to display all the results, in the query I get 129 results. But when I display it on the page I only get one row. I have used very similar code to get multiple results before, so I know it`s something simple, but I just can't get it. Any thoughts would be greatly appreciated!
<?php
$sql = "SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber";
$sql1 = "select dataplan as currentplan from maindata GROUP BY phonenumber";
$sql2 = "SELECT DISTINCT phonenumber AS value_sum1 FROM maindata";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
$result1 = mysql_query($sql2);
if (!$result1) {
echo "Could not successfully run query ($sql1) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result1) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
$result2 = mysql_query($sql2);
if (!$result2) {
echo "Could not successfully run query ($sql2) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result2) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)){
echo "<TABLE id='display'>";
echo "<td><b>Data Usage This Period: ". ROUND ($row["value_sum"],2) . "MB</b></td> ";
}
while ($row1 = mysql_fetch_assoc($result1)){
echo "<TABLE id='display'>";
echo "<td><b>Data Plan: ". $row1["currentplan"] . "</b></td> ";
}
while ($row2 = mysql_fetch_assoc($result2)){
echo "<TABLE id='display'>";
echo "<td><b>Phone Number: ". $row2["value_sum1"] . "</b></td> ";
}
?>
Updated based on suggestions - Very helpful thank you, I am very close, all values are correct but I can not get them in the same table, thoughts?
TRY To use ,
Loop in you code eg.
$result1 = mysql_query("SELECT DISTINCT phonenumber AS value_sum1 FROM maindata");
echo '<table>';
echo '<tr>';
echo '<th>id</th>';
echo '</tr>';
while($record = mysql_fetch_assoc($result))
{
echo '<tr>';
foreach ($record as $val)
{
echo '<td>'.$val.'</td>';
}
echo '</tr>';
}
echo '</table>';
Add
"LIMIT 0, 1" at the end of query
or
edit query like "select TOP 1 from....."
Lets make it easy on you ;)
have a look here how to use mysql_fetch_assoc
http://php.net/manual/en/function.mysql-fetch-assoc.php
follow the examples, you will be done in a sec.

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

Categories