incorrect result display from database - php

I have a database table that has 4 records with a column _id that auto increments. When I run a query to get all records, it works but it doesn't echo out all the ids, it only points to the first rows and echos it four times. I am using PHP and MySQLi. Here is my code
Code for querying
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
Code for display
do{
echo result['_id'];
}while($query->fetch_assoc());
It outputs 1111 instead of 1234. Please what is wrong?

You're fetching each of the 4 results, so it loops the appropriate number of times; but you're only assigning the fetched result to $result once, so that's the only _id value that gets echoed
do{
echo $result['_id'];
}while($result = $query->fetch_assoc())

You also can use a foreach loop :
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
foreach($result as $data){
echo $data['_id'];
}

Related

I want to fetch first five rows and display same 5 five rows at different places on single page using single query

I want to fetch first five rows and display same five rows at different places on single page, using single query
$cel_bir1=$db->query("SELECT * FROM tbl_birthday WHERE MONTH(Birthday_Date)=$month AND DAY(Birthday_Date)=$day LIMIT 4");
$get_bir=$cel_bir1->fetch(); $count=0;
while($get_bir1=$cel_bir1->fetch())
{
if($count++) echo ',';
echo $get_bir1['Name'];
}
So to get the first 5 rows, you can use Mysql Limit eg: Select * FROM mytable LIMIT 5.
Ok, typically what happens is, When using a PDO,your result-set is stored in an array.
$query = "Select * FROM mytable";
$statement = $db->prepare($query);
$statement->execute();
$productsinfo = $statement->fetchAll();//$productsinfo is the array in question
$statement->closeCursor();
Now to get the values in the array, you can loop through the array using a foreach loop like:
foreach($productsinfo as $productsinfomation):
$productid=$productsinfomation['productid'];
//you can echo $productid or anything you want to do with it here
endforeach;
There is no harm in repeating the foreach loop at different positions on your page.
Le'me know how it works for you.
Have fun coding.
$sql ="SELECT * FROM table_name LIMIT 0,5";
// $conn = your connection to database
$result = $conn->query($sql) or die($conn->error);
$html = '';
while($row = $result->fetch_assoc()){
$html.= $row['colum1'].'<br>'.$row['colum2'];
}
echo $html;
?>
// some more html code
<?php echo $html?>
// some more html code
<?php echo $html?>
// some more html code
<?php echo $html?>

Total Results versus Returned Results in PHP

I am using the following php to display the number of records returned in a db search.
$sql = "SELECT COUNT(id) FROM authorsbooks WHERE author LIKE '%$searchquery%'";
$query = mysqli_query($dbc, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
$textline1 = "Your Search Returned (<b>$rows</b>) Records";
<?php echo $textline1; ?>
This seems to work fine.
However, I cannot get the total number of records in the actual db to display.
Can anyone explain a way of getting the total number of records in the database. Btw, I have tried using $total = mysqli_num_rows($query) but it keeps returning 1 as an answer. Thanks for any help.
For that you've to fire another SQL query. Like this,
$sql = "SELECT COUNT(id) FROM authorsbooks";
$query = mysqli_query($dbc, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
echo $rows; // will return total rows in database.
SELECT COUNT(*) FROM authorsbooks
It's true that $total = mysqli_num_rows($query) should return one row. When you do a SELECT COUNT(*) then the query returns 1 row telling you how many matches there were in the table.

How to echo a dynamic html snippet based on a MySQL databse with PHP?

I'm trying to create an image gallery with a for loop iterated by a counter of database rows.
To make it more clear: for each row in the table, get only the id(primary index) number and the image link from the server (not all the info in the row). With that information, echo an HTML image tag with the link inside the 'src=' and the id inside the 'alt='.
Two problems here:
1- the id number of the first row isn't zero.
2- I don't have a clue on how to get the total number of rows and to fetch only those two informations (id and img source).
That way, I could subtract the total number of rows minus the id number of the first row and using it to put an end on the loop.
So how to echo this dynamic html snippet based on my databse with PHP?
My code:
<?php
$link = mysqli_connect('localhost','user','pass','db');
$result = mysqli_query($link, "SELECT * FROM `table`");
$rows = mysqli_num_rows($result);
/* free result set */
mysqli_free_result($result);
$caption = mysqli_query($link, "SELECT ");
for($i=0; $i < $rows; $i++) {
echo "<img src='$imageURL' alt='$idNumber'>";
}
?>
You need to use sql functions to iterate through the dataset results. Replace your for loop... replacing 'image_url_column' and 'id_number_column' with the name of your actual columns in your db:
while ($row = while ($row = mysqli_fetch_assoc($caption)){){
echo "<img src='".$row['image_url_column']."' alt='".$row['id_number_column']."'>";
}
This is a really easy task.
First we fetch the data from the database using mysqli_query to do the query.
Then we use mysqli_fetch_array to get an array so then we can loop through it and echo each item.
After that, we mysqli_num_rows to get the total number of rows returned and increment it by 1 so it is not zero.
NOTE: Since you are going to increment the id to avoid getting a '0', don't to forget to minus '1' if you intend to use that id for some server-side purpose.
$result = mysqli_query($link, "SELECT * FROM `table`"); //query sql
$result_array=mysqli_fetch_array($result, MYSQLI_ASSOC);//return array from the query
$count = mysqli_num_rows($result); //get numbers of rows received
foreach($result as $row){ //do a foreach loop which is really simple
echo "<img src='". $row['img_column_name_from_db'] . "' alt='" .$row['id_column_name_from_db'] + 1 . "'>"; //echo data from the array, + 1 to "$row['id_column_name_from_db']" so that 'alt=' doesn't start from '0'.
}
echo $count;
You can use the count function of MySql to achieve the total number of rows.
also you can do this via mysqli_num_rows() function of mysql.
Code:
<?php
$link = mysqli_connect('localhost','user','pass','db');
$caption = mysqli_query($link, "SELECT id, img, count(id) as total from table");
echo
//$rows = mysqli_num_rows($result);
while($rows = mysqli_fetch_assoc($caption)){
echo "<img src='$rows[img]' alt='$rows[id]'>";
echo "Total Rows: ".$rows[total];
}
?>

Using a php function in a while loop to get the values and the counts of the values in same column

I am trying to perform a query inside a while loop that is getting values from a column. I am trying to query first to get all my values from a column in my DB and then get the count of how many times that value is in that column.
Examples of output trying to get
myValue is in the column 3 times
myOtherValue is in the column 10 times
myOtherOtherValue is in the column 22 times
Example of code
$sql = "SELECT DISTINCT id, columnName FROM tableName";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
function myCount($id)
{
$query = "SELECT COUNT(*) FROM tableName WHERE name = '$id'";
$result = mysql_query($query);
$count = mysql_fetch_array($result);
}
echo "$id is in the column $count[0] times";
}
You can't define a function inside the while loop.
Using COUNT(*) with a GROUP BY name clause, then you could solve the problem with only one query.

PHP Zend - Execute to get a rowset and total number of records

I encounter some problem where i want to execute a SQL statement and get the total number of records + all the records.
$strSQL = "SELECT * FROM table WHERE ProjectID = 1 ";
$stmt = $db->query($strSQL);
$total = count($stmt->fetchAll());
while ($row = $stmt->fetch()){
..No More Record Shown here..
}
but there is no more record in the while loop after i execute fetchAll, i believe I need to get back to the first row or something, anyone know how to fix this?
You've already fetched all the records with fetchAll(). So when you call fetch(), there are no more records to read. Try storing the return value of fetchAll() in a variable and iterating through that. Something like this:
$strSQL = "SELECT * FROM table WHERE ProjectID = 1";
$stmt = $db->query($strSQL);
$allRows = $stmt->fetchAll();
$total = count($allRows);
foreach ($allRows as $row){
// process each $row
}

Categories