I only get one value in Mysql [duplicate] - php

This question already has answers here:
How do I iterate over the results in a MySQLi result set?
(2 answers)
Closed 1 year ago.
I am making a small browser game and I have a database where the high scores of the users are stored.
here an image of the database (name is the username and M1_CPM the score)
with the following code I am trying to get the top 10 values to later desplay them on a leaderboard:
$sql = "SELECT * FROM leaderboard ORDER BY M1_CPM DESC LIMIT 10";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
exit();
}
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
echo implode(",", mysqli_fetch_assoc($resultData));
The problem is that it always only echoes the highest score and not the top ten. Why?

The mysql_fetch_assoc() function returns only one row from a recordset as an associative array. to retrieve all rows use a while loop:
while($row = mysqli_fetch_assoc($resultData))
{
echo implode(",", $row);
}
Note: After the data is retrieved, this function moves to the next row in the recordset. Each subsequent call to mysql_fetch_assoc() returns the next row in the recordset.

Each time when mysqli_fetch_assoc($result) is accessed, the pointer moves to the next record. At last when no records are found, it returns null which breaks the while condition.
So you need first get the data with while and then use implode, sth like this
$rows = [];
while ($row = mysqli_fetch_assoc($resultData)) {
$rows[] = $row;
}
And then you can use implode, so your code will become like this
$sql = "SELECT * FROM leaderboard ORDER BY M1_CPM DESC LIMIT 10";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
exit();
}
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
$rows = [];
while ($row = mysqli_fetch_assoc($resultData)) {
$rows[] = $row;
}
echo implode(",", $rows);

Related

Display MySQL column value count only [duplicate]

This question already has answers here:
How to get count of rows in MySQL table using PHP?
(3 answers)
Closed 2 years ago.
How do I display this query result:
from MySQL onto a webpage, just like this:
?
I want to display the count only. I did run the same query through PHP but its returning '2'. The PHP code is below
<?php
//Connection for database
$conn = mysqli_connect("localhost", "root", "aaaaa", "db");
$query = "SELECT `gender`,COUNT(`gender`) FROM `reg` GROUP BY `gender`";
$result = mysqli_query($conn, $query);
if ($result)
{
// it return number of rows in the table.
$row = mysqli_num_rows($result);
if ($row)
{
printf("" . $row);
}
// close the result.
mysqli_free_result($result);
}
// Connection close
mysqli_close($conn);
?>
Please note that I have gone through other answers like this one but I can't really find my way through, I want the value count only not the total number of all rows in the table, .e.g. count for 'Male'.
You're using mysqli_num_rows(), which returns the number of rows in the result, not the actual data in the result. For that you need to use mysqli_fetch_assoc().
Your could would become:
$query = "SELECT `gender`,
COUNT(`gender`) AS `count`
FROM `reg`
GROUP BY `gender`";
$result = mysqli_query($conn, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$gender = $row['gender'];
$count = $row['count'];
echo "$gender = $count<br>";
}
mysqli_free_result($result);
}
Note that I slightly changed your query to make the count accessible.

mysqli_fetch_assoc only returning one result, even though there is more [duplicate]

This question already has answers here:
How to solve PHP error 'Notice: Array to string conversion in...'
(6 answers)
Create PHP array from MySQL column
(12 answers)
Closed 2 years ago.
When I ran the following query in PHPMyAdmin, it returned the correct number of results. However when I try to echo the results in PHP, it only outputs one result, even when there is more thn one. How do I fix this so that every result is displayed?
$sql1 = "SELECT userFirstname FROM users WHERE userID IN (SELECT userID FROM note_editors WHERE noteID = (SELECT noteID FROM notes WHERE uniqueID = ?))";
$stmt1 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt1, $sql1)) {
header("Location: note-premium.php?error=sql");
exit();
}
else {
mysqli_stmt_bind_param($stmt1, "s", $unique);
mysqli_stmt_execute($stmt1);
$result1 = mysqli_stmt_get_result($stmt1);
while ($row1 = mysqli_fetch_assoc($result1)) {
$names = $row1['userFirstname'];
}
}
echo($names);
Second attempt: I tried creating an array. But this just outputs the word array and the error message, "Notice: Array to string conversion". Why?
$sql1 = "SELECT userFirstname FROM users WHERE userID IN (SELECT userID FROM note_editors WHERE noteID = (SELECT noteID FROM notes WHERE uniqueID = ?))";
$stmt1 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt1, $sql1)) {
header("Location: note-premium.php?error=sql");
exit();
}
else {
mysqli_stmt_bind_param($stmt1, "s", $unique);
mysqli_stmt_execute($stmt1);
$result1 = mysqli_stmt_get_result($stmt1);
$column = array();
while ($row1 = mysqli_fetch_assoc($result1)) {
$column[] = $row1['userFirstname'];
}
}
echo($column);
As you're looping through the results and storing the value of the column 'userFirstName' in $names, you're overwriting the previous value stored in it.
You've got two options - display the value as you're looping through the results, or store the value in an array and then display that afterwards.
Option 1 - display the value as you're looping through the results:
while ($row1 = mysqli_fetch_assoc($result1)) {
echo $row1['userFirstname'];
}
Option 2 - store the values in an array and display that after the loop
$names = [];
while ($row1 = mysqli_fetch_assoc($result1)) {
$names[] = $row1['userFirstname'];
}
foreach($names as $name) {
echo '<p>'.$name.'</p>';
}
Obviously you can customise how you want to loop through the array values and display them. I've wrapped each value in a <p> tag so that they display on a new line. If you just want to display the unformatted contents of the array, use print_r($names)

Foreach implemented on finding array data finds only one data

Ive used two queried in a function. FIrst query to find an array of data. And second query is to select rows as per checking the array data from the first query. But the overall function return only one row data.
function getCartItems($conn)
{
$cust_id=$_SESSION['cust_id'];
$stmtSelect1 = $conn->prepare("SELECT product_id FROM tbl_cart WHERE cust_id=cust_id");
$stmtSelect1->bindParam('cust_id',$cust_id);
$stmtSelect1->execute();
$product_id= $stmtSelect1->fetchAll();
foreach($product_id as $productid) {
$stmtfetch = $conn->prepare("SELECT * FROM tbl_item WHERE product_id=:products_id");
$stmtfetch->bindParam(':products_id',$productid['product_id']);
$stmtfetch->execute();
$datas = $stmtfetch->fetchAll();
print_r($datas);
exit();
}
}
First of all, your code has typos (Missing ":" before parameter, product_id/products_id).
This should work:
$cust_id=$_SESSION['cust_id'];
$stmt = $conn->prepare("SELECT tbl_item.* FROM tbl_cart, tbl_item WHERE tbl_cart.cust_id = :cust_id AND tbl_item.product_id = tbl_cart.product_id);
$stmt->bindParam('cust_id',$cust_id);
$stmt->execute();
$rows = $stmt->fetchAll();
foreach($rows as $row)
{
print_r($row);
}

PHP PDO - incremental for loop that fetches the next array row with each loop

I'm in the process of updating my old mysql database techniques to prepared pdo statements. I'm all good with while loops while($row = $result->fetch()) however how would I do the following with PDO prepared statements?
$sql = "SELECT * FROM table WHERE id=".$id;
$result = mysql_query($sql) or die(mysql_error());
$loop_count = mysql_num_rows($result);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = mysql_fetch_array($result);
echo $loop_row['field'];
}
I've tried this but with no joy:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_count = $result->rowCount();
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = $result->fetch();
echo $loop_row['field'];
}
Thanks!
UPDATE: The reason for using a for loop instead of a while loop is the ability to paginate the results, otherwise I would just put LIMIT 7 on the end of the SQL query.
To properly count rows with PDO you have to do this -
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$rows = $result->fetch(PDO::FETCH_NUM);
echo $rows[0];
But you would be better off using LIMIT in your query if all you want to do is get a static number of results.
In addition you're making your loop overly complex, there is no need to test for a range in the for condition just set the static number unless you're doing something weird, like possibly pagination.
You can try it this way:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_rows = $result->fetchAll();
$loop_count = count($loop_rows);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
echo $loop_rows[$row]['field'];
}
As requested by the OP, here's an example of PDO prepared statements using LIMIT and OFFSET for pagination purposes. Please note i prefer to use bindValue() rather than passing parameters to execute(), but this is personal preference.
$pagesize = 7; //put this into a configuration file
$pagenumber = 3; // NOTE: ZERO BASED. First page is nr. 0.
//You get this from the $_REQUEST (aka: GET or POST)
$result = $conn->prepare("SELECT *
FROM table
WHERE id= :id
LIMIT :pagesize
OFFSET :offset");
$result->bindValue(':id', $id);
$result->bindValue(':pagesize', $pagesize);
$result->bindValue(':offset', $pagesize * $pagenumber);
$result->execute();
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
This gives you the complete resultset of rows, limited to your required page. You need another query to calculate the total number of rows, of course.
What you could try is:
//Get your page number for example 2
$pagenum = 2;
//Calculate the offset
$offset = 7 * $pagenum;
//Create array
$data = array();
$result = $conn->prepare("SELECT * FROM table WHERE id= ? LIMIT 7 OFFSET ?");
$result->bind_param("ii", $id,$offset);
$result->execute();
$resultSet = $result->get_result();
while ($item = $resultSet->fetch_assoc())
{
$data[] = $item;
}
$result->close();
//echo resultSet you want
var_dump($data);

Distinct SQL / PHP Behaviour (Only 1 Row Returned)

Bit of an issue with my PHP / SQL here. This is the code:
Code:
$query = "SELECT DISTINCT student FROM classes LIMIT 100";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
print_r($row);
Having run the query manually I get about 40 returned values. All good there. However when I do the print_r, I'm only getting the first returned value i.e. The $row array only has one entry. Link and db are fine, it just appears to be my array handling.
Any Thoughts?
The function mysqli_fetch_array only fetches one row at a time. Consider using it in a loop:
while($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
print_r($row);
}
You need to loop through the returned rows. Try this instead:
$query = "SELECT DISTINCT student FROM classes LIMIT 100";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
print_r($row);
}

Categories