Looping Through PHP Array from SQL - php

I have the following code, which Im using to try loop through an array, however it is printing nothing:
$getdata = "SELECT TimeDate, Percent FROM UserHistory";
echo $getdata;
$dataresult = mysqli_query($con,$getdata);
while($datarray = mysqli_fetch_array($dataresult));
{
echo $datarray['TimeDate'];
}
If I replace the while loop with $datarray = mysqli_fetch_array($dataresult); and then echo $datarray[0] or echo $datarray[1] it prints out values, but only the first set of results.

Use mysqli_fetch_assoc instead of mysqli_fetch_array and everything will be fine.
mysqli_fetch_array does not assign column names as indexes. Thats why numeric indexes work, but named inexes don't.
There is an error in code too... ; finishes while in a line it starts. Remove it.

Remove ';' from while($datarray = mysqli_fetch_array($dataresult));

Related

PHP array created inside for loop but not printing

I created a script to get data from a mysql table for every year and put into array of respective year. I checked the sql and the while loop iteration is working.
<?php
mysql_select_db($database_hari,$hari);
$start=2013 ;
$end=2015;
$xdata=array();
for($year=$start;$year<=$end;$year++){
${"y".$year}=array();
$i=0;
$query=mysql_query("SELECT tld_master.location,tld_dose.year, AVG(tld_dose.dose)*4 as avgdose from tld_master left join tld_dose on tld_master.tldno=tld_dose.tldno where tld_master.site='F' and tld_dose.year=$year GROUP BY tld_dose.year, tld_dose.tldno");
while($result=mysql_fetch_array($query)){
$xdata[$i]=$result['location'];
${"y".$year."[".$i."]"}=$result['avgdose'];
$i++;
}
}
print_r($y2015);
?>
Print displays "Array()"
But if I am echoing each array value inside for loop it prints. Where is the mistake?
Although there are ways to solve your problem with variable variables, I suggest you take different approach. What if year is a value you do not expect? It can easily lead to confusion. Instead you can use an array that you can iterate through without knowing the exact value of the year.
$yearArray = array();
for($year=$start;$year<=$end;$year++){
$sql = "SELECT
tld_master.location,tld_dose.year, AVG(tld_dose.dose)*4 as avgdose
FROM tld_master
LEFT JOIN tld_dose on tld_master.tldno=tld_dose.tldno
WHERE tld_master.site='F' and tld_dose.year={$year}
GROUP BY tld_dose.year, tld_dose.tldno";
$query = mysql_query($sql);
$yearArray[$year] = array();
while($result=mysql_fetch_array($query)){
$xdata[] = $result['location'];
$yearArray[$year][] = $result['avgdose'];
}
}
Now you can print the $yearArray variable to see your actual results. And you can use it easily.
print_r($yearArray["2015"]);
${"y".$year} = array()
creates a variable named $y2015, holding an array. The code
${"y".$year."[".$i."]"} = ...
creates an oddly named variable $y2015[0], which is completely unrelated to the variable $y2015. You want:
${"y".$year}[$i] = ...
You override your array value with this statement ${"y".$year."[".$i."]"}=$result['avgdose']; Try to use this one instead: ${"y".$year."[".$i."]"}[]=$result['avgdose'];

mysqli fetch_array() is only turning first row of retrieved data into an array

What seems to be happening is $result_tag is only holding the first row of the sql data retrieved.
When I run the result query on SQl in returns a table with multiple rows.
However, when I var_dump() it, it only returns the first row and nothing else.
while($row = $results->fetch_array(MYSQLI_BOTH)) {
echo ....stuff that dont matter
//Now I want some SQL results based on a result from ^^^ $row['ID']
$result = $conn->query("SELECT tags.Tag FROM tags WHERE tags.results_ID =".$row['ID'] );
$result_tag = $result->fetch_array(MYSQLI_NUM);
//I got the results. Now I want to compare them to another array '$explode'
//and echo out elements that are the same
foreach($explode as $explodeValue){
foreach($result_tag as $tag){
if($tag == $explodeValue){
echo $explodeValue;
}
}
}
}//end of 1st while
You want to use fetch_all(); fetch_array() returns just one row (as an array)
See http://php.net/manual/en/mysqli-result.fetch-all.php
This is in fact what the outermost while is doing, fetching one row at a time with fetch_array()
Change to
$result = $conn->query("SELECT * FROM tags WHERE results_ID =".$row['ID'] );

while loop is not working upon selecting multiple colums from a table

i have a table with 5 columns like TABLE(a,b,c,d,e).
now i want to select all the columns from TABLE.but the script is not workling once the while loop starts.
my php code is:
include_once $_SERVER['DOCUMENT_ROOT'].'/include/db.inc.php' ;
$sql="select * from TABLE";
$result = mysqli_query($link,$sql );
if (!$result)
{
include_once "wall.html.php";
echo'<tr><td align="center"> OOOOPPPPPSSS!!!SORRY,UNABLE TO DISPLAY LATEST 25 TOPICS</td></tr>';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$as[]=$row['a'];
$bs[]=$row['b'];
$cs[]=$row['c'];
$ds[]=$row['d'];
$es[]=$row['e'];
}
foreach($as as $x)
{
$name=$x;
}....................and so on
i have checked and debuged in many ways.what i noticed the script is not executing after while loop.
you forgot to write $ before variables:
$as[]=$row['a'];
^------------
bs[]=$row['b'];
cs[]=$row['c'];
ds[]=$row['d'];
es[]=$row['e'];
What about using array_push()? Also, use print_r() for $as[] and all the arrays you got and paste the output here so we get a clearer idea of what the issue exactly is.
Try this and tell what print_r() function is printing so that we can identify the problem.
while ($row = mysqli_fetch_array($result))
{
$as[]=$row['a'];
$bs[]=$row['b'];
$cs[]=$row['c'];
$ds[]=$row['d'];
$es[]=$row['e'];
}
print_r($as);
foreach($as as $x)
{
$name=$x;
}
First remove the brackets from $as[], the result of $row['a'] will not be an array.
And that's the reason the foreach is not working, you're not getting an array back.
If the resulting $as is empty, but there is something in your database, make sure the rownames are valid.
Use $row[0] instead of $row['A'].
Debug your code using print_r($row) to the see the contents of the results.

My fetch array is not working

I'm trying to pull an array to use on another query but it's not working, because the last comma.
<?php
include"connection.php";
$pos = mysqli_query($not,"SELECT * FROM equipos");
$logos = array();
while($row= mysqli_fetch_assoc($pos)){
$logos[] = "<br>'".$row['abrv']."'=>"."'".$row['logo']."'";
}
$logos = implode(",", $logos);
$enjuego = mysqli_query($not,"SELECT * FROM partidos WHERE dprt='ftbls'");
while($part=mysqli_fetch_array($enjuego)){
$liga=$part['serie'];
$eq1= $part['eq1'];
$eq1s= strtoupper($eq1);
$eq2= $part['eq2'];
$eq2s= strtoupper($eq2);
echo $logos[$eq1].'<br>';
}
?>
It gives me the same error over and over again.
This is the closest I came but just doesn’t work.
Can someone tell me what am I doing wrong?
The error I get is: Warning: Illegal string offset 'gua' in line 22
You have several problems with your code:
You never created an array
You constantly overwrite $logos
Your usage of substr_replace() indicates a deeper problem.
Here's a better approach:
Build the array.
$logos = array();
while($row= mysqli_fetch_assoc($pos)){
$logos[] = "<br>'".$row['abrv']."'=>"."'".$row['logo']."'";
}
There are many ways condense an array into a string. I encourage you to browse the manual on PHP Array Functions. In your case, you are interested in implode()
$logos = implode(",", $logos);
Note: The value for $logos smells. You should construct your arrays to hold data, not formatting.
For example:
$logos[$row['abrv']] = $row['logo'];
Output:
print_r($logos);
What you want can be achieved in many ways, but let's look at your code, there are quite a few things wrong in there.
Semantically meaningless variable names like pos, not, equipos, abrv. Only logo and result are good variable names.
Using the * selector in database queries. Don't do that, instead select the exact fields you need, it's better for performance, maintainability, code readability, testability, ... need I say more?
Fetching per row and running code on each row when what you actually want is an array containing all rows. Solution:
$result = mysqli_query($not, "SELECT * FROM equipos");
$logos = mysqli_fetch_all($result, MYSQLI_ASSOC);
Concatenating subarrays by using strings, that's not how it works, what you could do:
while($row = mysqli_fetch_assoc($result))
{
$logos[][$row['abrv']] = $row['logo'];
}
But as I said, that's not necessary.
Overwriting your variable $logos with each iteration of the loop. You'd need to do $logos[] = ....
Typically, implode is useful for such cases.
Without knowing what exactly you want to do, take this as a first hint:
$logos = array();
while($row= mysqli_fetch_assoc($pos)){
$logos[] = "<br>'".$row['abrv']."'=>"."'".$row['logo']."'";
}
$logos = implode(",", $logos);
The simplest way I would have thought is just to change the query and fetch the array into that -
<?php
include_once("connection.php");
$result = mysqli_query($not,"SELECT abrv, logo FROM equipos");
$rows = mysqli_fetch_array($result, MYSQLI_ASSOC);
// display the result
echo "<pre>"
print_r($rows);
echo "</pre>"
?>

php / mysql select- this is an easy one

I have this code.
<?php
require('connection/conn.php');
mysql_select_db($db_name,$ligação);
//$rsArticle = mysql_query("CALL get_article(1,518)");
$rsArticle = mysql_query("SELECT * FROM tblarticles WHERE ArticleID = 518");
while($rowArticle = mysql_fetch_array($rsArticle)){
echo $rowArticle;
}
?>
And instead of getting the text that exists in the database I just get the word: Array
The line that is commented its for calling a stored procedure. In a desperate measure I made a simple select, in the next line
Can anyone explain me what I'm doing wrong??
Thanks
The reason that you are getting the word Array is because what you are echoing is an Array. Use something like echo $rowArticle['column-name']; to echo the data from a specific column of your query.
You can't echo an array. try print_r() instead
if you want the values individually, do something like this:
while ($row = mysql_fetch_array($rsArticle, MYSQL_NUM)) {
//echo the first column of the record (index 0)
echo $row[0];
}
look in the php.net documentation for more info
mysql_fetch_array returns an array with elements for every field in your database table.
Either print the whole array with print_r() or use echo $rowArticle[COLOUMN_NAME] to echo certain values from your resultset.
mysql_fetch_array() returns you the array, when you use echo is actually return the object type in case of array.
use print_r($rowArticle); instead of echo.

Categories