PHP array created inside for loop but not printing - php

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'];

Related

Foreach loop, what did I do wrong?

Please see below code
$template->customer = $rephome->getCustomer($user_id);
foreach($template->customer as $value){
echo $value->customer_id;
}
The first line of code will get result of a query. it was fetched as object.
the second line of code will echo out all of the customer id field from the query result. This works fine. it will echo out 1234567.... to however many id there is.
however if I change the code to like the one below, the echo will only get the first customer_id. ie. 1
$template->customer = $rephome->getCustomer($user_id);
foreach($template->customer as $value){
$something = $value->customer_id;
}
echo $something;
so the question is what is the correct way of assigning the list of results to $something. so I can use $something as a list of ids to be used to run other querys.
in another word. I am trying to use result of first query to run a second query.
$template->customers = $rephome->getCustomer($user_id);
foreach ($template->customers as $value){
$template->orders = $rephome->getOrder($value->customer_id);
}
the above code give me the same result as echo. I will get all the customer id as intented but I will only get repeating order information that is assoicated with first customer id. instead of different orders associated to different customer id.
Yes of course, cause you are overwriting the $something variable each iteration of the foreach loop and echo the result afterwards.
A way to solve this is by using an array:
$something = array();
foreach($template->customer as $value){
$something[] = $value->customer_id;
}
This way you are adding a value to the array each iteration.
so the question is what is the correct way of assigning the list of
results to $something. so I can use $something as a list of ids to be
used to run other querys.
To use the ID's for another SELECT query, so it will only return records associated with the id's inside the array, you can do this for example:
$sql = 'SELECT * FROM `table`
WHERE `id` IN (' . implode(',', array_map('intval', $something)) . ')';
Which will result in something like:
$sql = 'SELECT * FROM `table` WHERE `id` IN (1,2,4,6,7,10)';
Does this answer your question?
On this code:
foreach($template->customer as $value){
$something = $value->customer_id;
}
$something will be overrriten on each loop for a new value. So, on last line, your code will output the last value of resultset´s $value->customer_id.
Got it ??
So, use an array:
$something = array();
foreach($template->customer as $value){
$something[] = $value->customer_id;
}
Try this within your loop:
$something[] = $value->customer_id;
and then outside your loop:
print_r($something);

I can't get the value of a query outside the loop

I'm using PHP and I do a mysql query and I save the result of this query in an array. Then, I use a loop and into the loop i do another mysql query using the values of the array in the where clause. It's right but if I try to get the result of the query outside the loop I can't.
Here an example code
$result=$mysqli->query("SELECT code FROM referee");
$i=0;
$arcode=array();
while($row=$result->fetch_array()){
$arcode[$i]=$row["code"];
$i++;
}
for($j=0;$j<sizeof($arcode);$j++){
$result2=$mysqli->query("SELECT code, time FROM match where referee_code IN ($arcode[$j])");
}
/*Here I can't get the result values*/
$matcode=array();
$hour=array();
$k=0;
while($row2=$result2->fetch_array()){
$matcode[$k]=$row2["code"];
$hour[$k]=$row2["time"];
}
If I put all in the same loop I get the result repeated (This code is one example of all my code but the idea is the same in the rest).
You are overwriting the result set values into $result2.
The correct method would be something like:
$matcode = array();
$hour = array();
$result2 = $mysqli->query("SELECT code,
time
FROM `match`
WHERE referee_code IN (SELECT code
FROM referee)");
while ($row2 = $result2->fetch_array())
{
$matcode[] = $row2["code"];
$hour[] = $row2["time"];
}
You may change the index values according to the way you want the array to look like.
Also match is a reserved word. So you would have to enclose it in backticks.
If you want to print complete data then try this :
$matcode = array();
$hour = array();
$result2 = $mysqli->query("SELECT code,
time
FROM `match`
WHERE referee_code IN (SELECT code
FROM referee)");
$completeData=array();
while ($row2 = $result2->fetch_array())
{
$completeData[] = $row2;
}
print_r($completeData);
Don forget to accept answer if it helps :)

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>"
?>

Trying to get field data to fit into if inarray() check

Just wondering if anyone can help me with this problem...
I want to be able to check if a certain ID (user for example is logged on) The ID's of these users will be pulled from a table, and then fed into an array and then checked if it is in there.
However when I pull the data the if inarray() no longer works as it would if I just typed it in straight within the code instead of pulling it.
I want to pull approved ID's through so they can access a certain link essentially!
Any help would be appreciated! Thanks!
<?php
mssql_select_db("$ins", $con);
$result = mssql_query("SELECT ID FROM Event WHERE EventPublic LIKE 'Yes' AND EventDate >= GETDATE() -1 ORDER BY EventDate ASC ");
while($row = mssql_fetch_array($result))
{
$test = "". $row['ID'] .",";
}
$tests = explode(',', $test);
if (in_array("2, 48", $tests)) {
echo "WOO";
}
else
{
echo "BOO";
}
mssql_close($con);
?>
in array should be an actual array
in_array(array('2', '48'), $tests)
also, it would be better to put
$tests = array();
before the while loop, then change the code inside the loop to read
$tests[] = $row['ID'];
then you can do away with the '$tests = explode(...' line.
Your having the issue with your in_array test because you are comparing an array and with a string in the following line:
if (in_array("2, 48", $tests))
The above line checks if the string "2, 48" exist in the array. But the array will have 2 as one element and 48 as a separate element. To fix this you can search for each element individually with something like:
if(in_array('2',$tests) || in_array('48',$tests))

PHP and MYSQL "while" prints only one value

Hey all i have a mind bug with this wile loop , i am a bit of a noob
$sql_advanced_bio = mysql_query("SELECT * FROM bio_details WHERE mem_id='$id'");
while($row = mysql_fetch_assoc($sql_advanced_bio)){
$bio_time_family = $row["bio_time_family"];
}
So this is the php now in my HTML i have this
*php echo $bio_time_family *
Why dose it echo only one value ?
SIMPLE ANSWER
so i tried somethingh easier like this $bio_fun_family .= $row["bio_fun_family"].",";
and then this
$bio_fun_family = substr($bio_fun_family,0,-1);
I added the .next to the =
It appends the values
You need to store the values in an array, otherwise you're just overwriting one variable each time, so you'll just end up with the last value.
You also need to use a loop to echo out each value in the array.
$sql_advanced_bio = mysql_query("SELECT * FROM bio_details WHERE mem_id='$id'");
$bio_time_family = array();
while($row = mysql_fetch_assoc($sql_advanced_bio)) {
$bio_time_family[] = $row["bio_time_family"];
}
And then for the output;
foreach($bio_time_family as $b) {
echo($b . '<br />');
}
With each iteration of the while loop, you're assigning to $bio_time_family the newly extracted value. If you'd like to make an array of the, instead, use $bio_time_family[] = $row["bio_time_family"];
Because every time you run through the loop you're re-assigning $bio_time_family to the next row's value. Try calling echo directly in your loop or add the row to an array, then loop through that and output the rows

Categories