This question already has answers here:
Resetting array pointer in PDO results
(7 answers)
Closed 9 years ago.
I am fetching the results from a db with PDO::FETCH_ASSOC. The issue is that I am doing it twice in the same file. Is that a known issue? What would be the alternative?
Here is my code:
FIRST TIME
while($row = $ordersQuery->fetch(PDO::FETCH_ASSOC))
{
$totalAmount += $row['clientPrice']/100;
}
echo $totalAmount;
SECOND TIME
while($row = $ordersQuery->fetch(PDO::FETCH_ASSOC))
{
....
}
Whenever I remove the first fetching, the second works fine. If I have both, the second does not return anything.
Thanks!
You can't fetch from the DB multiple times like this. Do this instead:
$orders = $ordersQuery->fetchAll(PDO::FETCH_ASSOC);
...
foreach ($orders as $val) {
// stuff 1
}
...
foreach ($orders as $val) {
// stuff 2
}
Use fetchAll() which will return an array. You then can loop through it as many times as you want:
$orders = $ordersQuery->fetchAll(PDO::FETCH_ASSOC);
Related
This question already has answers here:
How to load MySQLi result set into two-dimensional array?
(3 answers)
Closed 6 years ago.
Looking at all the questions are using the depreciated mysql_fetch_assoc/array, hence I don't think that this is a duplicate question.
I have a MySQL table with 5 columns,
ID | NAME | AGE | GENDER | HEIGHT
If I want to store the values of NAME, AGE, GENDER in a PHP array,
$query=$mysqli->query("SELECT NAME,AGE,GENDER FROM TableName")
while($result = $query->fetch_assoc()
{
$array = [];
}
Will my array be stored in the format of
$array=[[Name,Age,Gender],[Name,Age,Gender]]?
If not, what would be my approach in doing this?
It's very simple. You just have to append the result variable in to main array. Like this,
$array =array();
while($result = $query->fetch_assoc()
{
$array[] = $result;
}
$result is an array (fetch_assoc it returns result-set in array) so just append that into main array to get the desired result. ($array=[[Name,Age,Gender],[Name,Age,Gender]])
$data =[];
$i=0;
while($result = $query->fetch_assoc(){
$data[$i][] = $result;
$i++;
}
This question already has answers here:
Removing last comma from a foreach loop
(9 answers)
Closed 6 years ago.
How to remove last comma from the output of a foreach() loop?
Can someone please help modify this code for me.
$sth = $dbh->query('SELECT * FROM `stage5` ORDER BY `stage5`.`lenght` DESC');
$sth->setFetchMode(PDO::FETCH_ASSOC);
$result = $sth->fetchAll();
foreach($result as $r) {
echo $r['lenght'], ",";
}
This prints
105.4,102.1,
Below would be correct
105.4,102.1
I have read many posts related to this but, I can't get it working and I don't get it. Any help is appreciated!
One way to solve this is to not echo out the commas in the foreach loop. Put the data you want to echo into an array, then use implode.
$output = array();
foreach($result as $r) {
$output[] = $r['lenght'];
}
echo implode(',', $output);
I would just take a functional approach:
<?php
$result = $sth->fetchAll();
echo implode(',', array_column($result, 'length'));
Note that array_column() requires PHP 5.5+.
This question already has answers here:
How to check whether an array is empty using PHP?
(24 answers)
Closed 7 years ago.
I am creating a form to filter the data on my database (Mysql) with queries based on the user's selections.
I am using this code to generate the "data.json" file:
How can I improve the code and check if the array returns empty values? and instead of drawing a chart without bars tells the user to change the selections.
<?php
$rows1 = array();
$rows1['name'] = $varLabel;
while($rr = mysqli_fetch_array($TableData)) {
$rows1['data'][] = $rr[$varLabel];
}
$rows = array();
$rows['name'] = "Registros";
foreach($TableData as $r) {
settype($r['cnt'], "integer");
$rows['data'][] = $r['cnt'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
file_put_contents("data.json", json_encode($result));
?>
Since your array is created by looping over your database result set which you access using mysqli, Use mysqli_num_rows
if(mysqli_num_rows($TableData)==0)
{
// no data
}
This question already has answers here:
Mysqli query doesn't work twice
(2 answers)
Closed 5 years ago.
I'm retrieving some data from a mysql database. There are two loops which uses the same result set.
while ($row = mysqli_fetch_array($newsQuery)) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
}
This loop ends with success. then in the same page I have the following loop.
while ($row = mysqli_fetch_array($newsQuery)) {
echo $row["news_content"];
}
This loop doesn't return anything even if there are content in the table. When I try it in the first loop. the content is displayed correctly. Any idea on what I'm doing wrong.
From PHP's mysqli_fetch_array DOCS:
Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.
You are using a 'while' loop on $row = mysqli_fetch_array($newsQuery)
This means the loop will keep going untill mysqli_fetch_array($newsQuery) returns NULL.
This is the reason why you cant use that loop again, since mysqli has finished fetching the results and the mysqli_fetch_array($newsQuery) now returns NULL untill you make a new query.
Try populating a variable with the results first, then loop on that variable:
$results = array();
while ($row = mysqli_fetch_array($newsQuery)) {
$results[] = $row;
}
foreach ($results as $key => $row) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
}
foreach ($results as $key => $row) {
echo $row["news_content"];
}
While it is best to avoid logic that results in looping through a result set twice, if necessary you need to reset the result set back to the start:-
mysqli_data_seek($newsQuery, 0);
Because you already fetch the value of $newsQuery Try this code
//temporary save the news content into array
$content = array();
$x=0;
while ($row = mysqli_fetch_array($newsQuery)) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
$content[$x]= $row["news_content"];
$x++;
}
and if you want to retrieve it
//now retrieve it
for($y=0; $y<count($content); $y++)
{
echo $content[$y]+"<br/>";
}
This question already has answers here:
Creating an array from a MySQL table
(2 answers)
Closed 10 years ago.
I am using PHPlot to make a graph.
I have an issue in generating the array from a MySQL table.
Basivally, I want to array is as follows:
$values = array($arrayx);
array('a',-3),
array('b',5),
array('c',7),
array('d',8),
array('e',12),
array('f',-6),
//);
$graph->SetDataValues($values);
$graph->SetXTickPos('none');
$graph->SetXTickLabelPos('none');
Part of the code where I tried to retrieve values from table to feed the array
$query="SELECT * FROM tasks";
$result=mysql_query($query);
//using a for loop to add values to the array
while ($resource=mysql_fetch_array($result)){
$thedate = $resource["date"];
$title = $resource2["title"];
$innerarray = "array('.$thedate.', $title),";
}
$values = array($innerarray).");";
$graph->SetDataValues($values);
$graph->SetXTickPos('none');
$graph->SetXTickLabelPos('none');
//Draw it
$graph->DrawGraph();
}
The way I'm doing the $innerarray and $values seems wrong. Can you please help me fix it?
Thank you
try replacing
$innerarray = "array('.$thedate.', $title),";
with
$innerarray = array($thedate, $title);
$new = array();
while(for condition ){
$new[] = '\''.thedate[$i].''\','.$title[$i].'\';
}
var_dump($new);
this an idea, you need to edit the code to make it working
I assume it is this that you want:
$sql="SELECT datefield, titlefield FROM tasks";
....
while (list($thedate,$thetitle) = mysql_fetch_array($result)) {
$values[] = array($thedate,$thetitle);
}
echo $values[0][0]; // will output your 1st date
echo $values[0][1]; // will output your 1st title