php while() loop within if / else not seeming to work - php

I've been confused about why this wont work! My query executes perfectly fine in all aspects, but when I added the if check on the $row value, the echo message goes as expected (if there are no results), but the else will not kick when there is a match in my query??? Why is this not working? Someone please ease my pain and set me straight!!
$row = mysql_fetch_array($result);
if (!$row) {
echo "Sorry brah. Nothing matches your search criteria.";
} else {
$i = 1;
while($row = mysql_fetch_array($result)) {
echo "$i - " . $row['first_name'] . " " . $row['last_name'] . " - " . $row['address'] . "<br />";
$i++;
}
}

$row = mysql_fetch_array($result); // this fetches the first row your result
...
in while loop you are again fecthing thr row from result. Which will not work if you have only one row in resul
use
if (mysql_num_rows($result) == 0) {
echo "Sorry brah. Nothing matches your search criteria.";
} else {
$i = 1;
while($row = mysql_fetch_array($result)) {
echo "$i - " . $row['first_name'] . " " . $row['last_name'] . " - " . $row['address'] . "<br />";
$i++;
}
}

try mysql_num_rows($result)==0 instead in the if statement

Related

Display results from DB using Bootstrap

I would like to retrieve my results from my DB in this format using Bootstrap.
Below is my PHP code that I'm currently using, the first entry I want the image to be bigger then the rest.
<?php
$article = mysqli_connect("localhost", "root", "", "blog");
// Check connection
if($article === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM news";
if($result = mysqli_query($article, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<container>";
echo "<row>";
echo "<th>id</th>";
echo "<th>title</th>";
echo "<th>body</th>";
echo "<th>image</th>";
echo "</div>";
while($row = mysqli_fetch_array($result)){
echo "<row>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['body'] . "</td>";
echo "<td>" . $row['image'] . "</td>";
echo "</row>";
}
echo "</div>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($article);
}
// Close connection
mysqli_close($article);
?>
I think you should have the condition to check for the first data in your loop to apply a bigger image size.
You can simply add condition:
$resultNum = 1;
while($row = mysqli_fetch_array($result)){
if($resultNum == 1) {
// TODO: show bigger image
} else {
// usual image
echo "<row>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['body'] . "</td>";
echo "<td>" . $row['image'] . "</td>";
echo "</row>";
}
$resultNum++;
}
Just make a counter and then do a condition using the first number of the counter
Your code simplyfied:
$query = mysqli_query($article, "SELECT * FROM news");
$n = 1; //start the counter
if(mysqli_num_rows($query) > 0){ //detect if have rows
foreach ($query as $key => $value) {
if($n == 1){
//print the big image
echo $value["id"];
}else{
//print the little image
echo $value["id"];
}
$n++;
}
}else{
echo "No data founded";
}

Why does fetch(PDO::FETCH_ASSOC) return false

I am trying to learn about PDO and while i am trying to return some values from database i keep getting false as return from my var_dump($row) and i can't figure out why.
This is my code
require("db.php");
$stmt = $db->query("SELECT * FROM names");
while($row = $stmt->fetch(PDO::FETCH_ASSOC));
{
echo $row['name'] . " " . $row['surname'] . "<br>";
var_dump($row);
}
The weird part is that when I do it like this it returns desired database records.
foreach($db->query("SELECT * FROM names") as $row){
echo $row['name'] . " " . $row['surname'] . "<br>";
}
Note: Yes i know i should be using prepared statements,but i haven't got to that part yet.
It's basically a typo caused by
// ↓this
while($row = $stmt->fetch(PDO::FETCH_ASSOC));
{
echo $row['name'] . " " . $row['surname'] . "<br>";
var_dump($row);
}
The semicolon before the brace disassociates the loop from the code in the braces, and it runs through the result set without doing anything.
You end up with false when you var_dump($row) because you've already fetched the last row, then the next fetch returns false.

How do I echo a div using SQL table row ID as ID for the div?

I have this PHP code, which fetches data from my SQL database called "comments".
This code prints out every comment in the table:
<?php
$sql = "SELECT id,name,email,number,text FROM comments";
$result = $conn->query($sql);
if($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<strong>ID:</strong><br> " . $row["id"] . "<br>";
echo "<strong>Navn:</strong><br> " . $row["name"] . "<br>";
echo "<strong>Email:</strong><br> " . $row["email"] . "<br>";
echo "<strong>Nummer:</strong><br> " . $row["number"] . "<br>";
echo "<strong>Melding:</strong><br> " . $row["text"] . "<br><br><br>";
}
echo '<div class = "white_line_comments"></div>';
} else {
echo "0 results";
}
This has worked fine so far, everything prints as it's supposed to.
Then I decided I wanted a way to give each individual comment some sort of identification to make them unique. I tried putting each single comment into its own div, using the SQLtable row id as id for the div.
However, when I try to access my webpage now, it tells me the website doesn't work (HTTP Error 500).
<?php
$sql = "SELECT id,name,email,number,text FROM comments";
$result = $conn->query($sql);
if($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
<div class='$row[' id'].'>";
echo "<strong>ID:</strong><br> " . $row["id"] . "<br>";
echo "<strong>Navn:</strong><br> " . $row["name"] . "<br>";
echo "<strong>Email:</strong><br> " . $row["email"] . "<br>";
echo "<strong>Nummer:</strong><br> " . $row["number"] . "<br>";
echo "<strong>Melding:</strong><br> " . $row["text"] . "<br><br><br>";
echo '</div>';
}
echo '
<div class="white_line_comments"></div>';
} else {
echo "0 results";
}
Any ideas on this? I guess I must've done something wrong when including the div, but I can't figure out what!
You have an error in this line after starting while loop:
echo "<div class ='$row['id'].'>";
It should be
echo "<div class ='". $row['id'] ."'>";
You should also configure your web server/hosting/localhost to throw a PHP error.
Read this if you are on localhost or your own server:
How can I make PHP display the error instead of giving me 500 Internal Server Error
Read this if you are using shared hosting: How do I displaying details of a PHP internal server error?
echo "<div class ='$row['id'].'>";
First line in while loop should look like this
echo "<div class = '".$row['id']."'>";
or
echo "<div class = '$row['id']'>"
You have mixed different apostrophe, try this:
echo "<div class ='" . $row['id'] . "'>";

PDO fetchObject() after fetchall(). returning false

I am new to PHP.
I am trying to display the details of employees in form of table.
But while($row = $result->fetchObject()) part is not executing, as $result->fetchObject() is returning false. Has it something to do with $rows = $result->fetchAll();?
Here's the code snippet.
$sql = "SELECT id, name, designation FROM employees";
if ($result = $pdo->query($sql)) {
$rows = $result->fetchAll();
$num_rows = count($rows);
if ($num_rows > 0) {
echo "<table>\n";
echo " <tr class=\"heading\">\n";
echo " <td>ID</td>\n";
echo " <td>Name</td>\n";
echo " <td>Designation</td>\n";
echo " </tr>\n";
while($row = $result->fetchObject()) {
echo " <tr>\n";
echo " <td>" . $row->id . "</td>\n";
echo " <td>" . $row->name . "</td>\n";
echo " <td>" . $row->designation . "</td>\n";
echo " </tr>\n";
}
echo "</table>";
} else {
echo "No employees in database.";
}
else {
echo "ERROR: Could not execute $sql. " . print_r
($pdo->errorInfo());
}
PDO's documentation is a little confusing on this, but the PDOStatement::fetch() method and its cousin fetchAll() return false when no more rows are available to return. The docs say it returns false on failure, and a lack of available rows counts as a failure.
Your initial call to fetchAll() gets all the rows from the PDOstatement result object and there are no more for the fetchObject() call to retrieve so it returns false.
You only need your initial call to fetchAll(), but you may need to set its fetch type to PDO::FETCH_OBJ if you did not previously set the default fetch type for your connection.
Then, you can replace your while loop with a simple foreach loop over the $rows array you already have. This has the added benefit of separating your display logic from your database query business logic a little more:
if ($result = $pdo->query($sql)) {
// Fetch them now, as objects
$rows = $result->fetchAll(PDO::FETCH_OBJ);
$num_rows = count($rows);
if ($num_rows > 0) {
echo "<table>\n";
echo " <tr class=\"heading\">\n";
echo " <td>ID</td>\n";
echo " <td>Name</td>\n";
echo " <td>Designation</td>\n";
echo " </tr>\n";
// $rows now has everything you need, just loop over it
foreach ($rows as $row {
echo " <tr>\n";
echo " <td>" . htmlspecialchars($row->id) . "</td>\n";
echo " <td>" . htmlspecialchars($row->name) . "</td>\n";
echo " <td>" . htmlspecialchars($row->designation) . "</td>\n";
echo " </tr>\n";
}
echo "</table>";
} else {
echo "No employees in database.";
}
else {
echo "ERROR: Could not execute $sql. " . print_r
($pdo->errorInfo());
}
Note also, that I added calls to htmlspecialchars() while writing output to HTML. That is always recommended, so that characters like < > & which have special meaning in HTML are properly encoded, and avoids cross-site scripting vulnerabilities if those values originated as user input.

printing [mysql_query] result in a table

I want to print mysql_query result in a table. I know how to do it but I am just confused. I tried this.
<?php
mysql_connect("localhost","root","") or die("Could not Connect.");
mysql_select_db("check") or die("Could not Select DB");
$table = "cc";
$i = 1;
$query = "select * from $table";
$sql = mysql_query($query);
if($sql){
echo "<table border='5'><tr>";
while($i<=2 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=4 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=6 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=8 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
echo "</tr></table>";
}
?>
As you can see it is written again and again with a slight change of 2,4,6,8 in the while loop. It works but the problem is I cant rewrite it again and again as when the website will go live it will have more than 1000 entries. Could You guys help me out by suggesting another way to do this?
""** I need it to be like these dots (dots represent records in the database) **"""
. . . .
. . . .
. . . .
THANKS in Advance.
Ramzy
<?php
mysql_connect("localhost","root","") or die("Could not Connect.");
mysql_select_db("check") or die("Could not Select DB");
$table = "cc";
$query = "select * from $table";
$sql = mysql_query($query);
if($sql){
echo "<table border='5'><tr>";
while($row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
echo "</tr></table>";
}
?>
while($row = mysql_fetch_array($sql)) {
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
I don't really see what's the problem here.
By the way you should never call you're array like this $row[id] but you should quote the key instead $row['id']; Because if a constant id exists it will screw up your code and also for performance reason.
Just use
$limit = 1000;//place any value you need here to limit the number of rows displayed
while ($i<=$limit && $row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
++$i;
}
Also, that limit is unnecessary if all you want is to flush every record to the output. You could just do
while ($row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
And it will stop as soon as there are no more records.
To print all database rows into an HTML-table, use:
echo '<table>';
$i = 0; // $i is just for numbering the output, not really useful
while($row = mysql_fetch_array($sql))
{
echo '<tr><td>' . $i . ' - ' . $row['id'] . ' : ' . $row['name'] . '</td></tr>';
$i++;
}
echo '</tr></table>';
here is a general function I use:
function query_result_to_html_table($res, $table_id = NULL, $table_class = NULL, $display_null = true)
{
$table = array();
while ($tmp = mysql_fetch_assoc($res))
array_push($table, $tmp);
if (!count($table))
return false;
echo "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" "
. ($table_id ? "id=\"$table_id\" " : "")
. ($table_class ? "class=\"$table_class\" " : "") . ">";
echo "<tr>";
foreach (array_keys($table[0]) as $field_name) {
echo "<th>$field_name";
}
foreach ($table as $row) {
echo "<tr>";
foreach ($row as $col => $value) {
echo "<td>";
if ($value === NULL)
echo "NULL";
else
echo $value;
}
echo "\n";
}
echo "</table>\n";
return true;
}
I Got The Answer.. I wanted it to be like this. I made this and It Actually Works.
<?php
$i = 1;
mysql_connect("localhost" , "root" , "") or die('Could not Connect.');
mysql_select_db("db") or die('Could not select DB.');
$query = "select * from `check`";
$sql = mysql_query($query) or die(mysql_error());
echo "<table border='5' width='50%'><tr><th>Name</th><th>Gender</th></tr></table><table border='5' width='50%'><tr>";
if($i<3){
echo "<td align='center'>".$row['name']."</td>";
echo "<td align='center'>".$row['gender']."</td>";
++$i;
} else {
echo "<td align='center'>".$row['name']."</td><td align='center'>".$row['gender']."</td>";
echo "</tr>";
$i = 1;
echo "<tr>";
}
}
echo "</table>";
?>
</div>
Thank You Guys For Your Support

Categories