PHP and MYSQL "while" prints only one value - php

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

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);

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

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 :)

while loop into in array

What am I trying to do is collect data from a while loop, store it into a variable. Then later in my code I see if some variable is equal to one of the values in the array and then to echo out the two other column values I got from the while loop but equal to the row that the value came from. I have tried a bunch different things and am so close but cant get it exactly.
while($row = mysql_fetch_assoc($query)){
$team[] .= "{$row['team']}";
$winslosses .= "({$row['wins']} - {$row['losses']})";
}
this returns something like
$team = (bears, badgers, wildcats)
$winslosses = ((42-24), (55-23), (32-21))
Then later in my code I want to see if its equal to a value in the array then echo $winslosses.
if(in_array(bears, $team) ) {echo '$winslosses';}
This shows all the wins and losses from each team. I want it only show me the record of the bears.
Any help would be great.
You can use array_search() to get the index of an item in an array. You can then use that index when querying $winlosses:
$team = array(bears, badgers, wildcats);
$winslosses = array("(42-24)", "(55-23)", "(32-21)");
$key=array_search(bears, $team);
echo $winslosses[$key]
results in:
(42-24)
Your best bet would be to store them in an associative array.
while($row = mysql_fetch_assoc($query)){
$winslosses[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Hope this helps
Your main problem is that you currently have $winslosses as a string, not an array, so you can't easily pull out the win/loss record for just one team.
There are several ways you could do this. The one that seems easiest to me would be to put it together as one array up front.
Something like...
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Then later on...
if(array_key_exists("bears",$teams)) {
echo $teams["bears"];
}
Or even better, store the wins/losses as a sub-array, so you have structured data that you can format however you want later on.
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = array("wins" => $row['wins'], "losses" => $row['losses']);
}
echo $teams['bears']['wins']; // for example
Use associative array:
while($row = mysql_fetch_assoc($query)){
$team[] = {$row['team']};
$winslosses[$row['team']] = "{$row['wins']} - {$row['losses']}";
}
Then retrieve it like this:
if(in_array(bears, $team) ) {
echo $winslosses['bears'];
}
As a matter of fact, if you do not need the names of the teams in a separate array, you can just use one associative array and then retrieve it.
if (array_key_exists('bears', $winslosses)) {
echo $winslosses['bears'];
}

Store a value from a database into a variable for use outside of a "while" in PHP

This is the relevant bit of my code:
while($row1 = mysql_fetch_array($result1)){
$pro_no = $row1['project_no'];
So outside of this "WHILE" i want to use $pro_no. How do i go about doing this?
Thanks
EDIT: Thanks, didn't realise i would not need a while loop
If you have only one row you can do
$row1 = mysql_fetch_array($result1));
$pro_no = $row1['project_no'];
or if you have mamy rows you can accumulate values in an array
$pro_no = array();
while($row1 = mysql_fetch_array($result1)){
$pro_no[] = $row1['project_no'];
}
At the end of while all the values from column project_no will be in your array
After the loop it will be filled with the last value from inside the loop. Therefore it makes sense to set it to a default value to make sure it ran trough the while().
Example:
$pro_no = 'DEFAULT VALUE';
while($row1 = mysql_fetch_array($result1)){
$pro_no = $row1['project_no'];
}
var_dump($pro_no);
// shorter and faster way of finding the last value:
$row1 = mysql_fetch_array($result1);
rsort($row1);
var_dump($row1[0]);
I'm guessing you're problem is that the value of $pro_no changes for each loop and you only reach the last one after the loop. Save them to an array instead to be able to use all later:
$pro_no[] = $row['project_no'];
Hope I understood the problem correctly
Since $proj_no will change each time the loop runs, you need to assign the values to an array, and access the array.
while($row1 = mysql_fetch_array($result1)){
$proj_array[] = $pro_no = $row1['project_no'];

Categories