while loop into in array - php

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

Related

Get selected value from database table?

im new in field of manipulating databases so i have a problem.
So after making a query to select all values from a table row with something like :
while($row = $result->fetch_assoc()) { }
For example if table has names in it we would get :
John
Bob
Steve
Mark
If we put these results in a form of a link or a button, is there any way to get their value?
i tried something like :
if (isset($_POST['result_button'])) {
$value =$row['name'];
}
I tried this when i put all the results from query in to a form of button, but that only pulls the last value from table row.
I tried putting results into array like :
$result= array();
$result[]=$row['name'];
echo $result[2];
I don't fully understand how arrays works so might have done something wrong there but from what i tried this works only if i put echo$result[0];
Ok, firstly:
$row = $result->fetch_assoc()
This does not work how you're expecting it to. What this is basically saying, is that for each returned value (from the MySQL query), store in $row for this iteration of the while loop.
So, in you're example, $row will first be John, then Bob, then Steve and finally Mark. They are not all stored in the variable at the same time. Bob overwrites John, etc.
I'm going to skip your second bit of code, as it's clear you do not have an understanding of arrays.
Arrays
There is plenty of material about arrays on the web. I'm not sure why you had to post the question here, however...
To define an array:
$my_array = array();
An array with values:
$my_array = array(
"bar",
"foo"
);
Assign variables to an array:
$my_array = array();
$my_array[0] = "Help" // $my_array[0] now contains "Help"
$my_array[1] = "Me"; // $my_array[0] now contains "Me"
So, taking you're final example:
$result= array();
$result[]=$row['name'];
echo $result[2];
You haven't stored anything in the 2nd element of the array.
This would be more appropriate:
$result= array();
$result[0] = $row['name'];
echo $result[0]; // This would print what was stored in $row['name']

PHP - Multidimensional Array

I am basically trying to fetch results from a SQL database and load that into a multidimensional array so i can use them later on in the page.
while($row = mysqli_fetch_array($result))
{
$send = array
(
array($row['Name'],$row['Email'],$row['Mobile'])
);
$count = $count + 1;
}
That is what i am using to get the results which if i print within the while loop it will echo all the results. However when putting it into the array it loads each result into the array as the first result. My initial plan was to use a counting variable to set where in the array the result was set to with this adding by one each time. I am not certain how to specify where to add the result i thought something along the lines of
$send = array[$count]
(
array.....
so i could then refer to the results as 0 to count length but i am not sure how to make this work. Or ,which i presume, if there is a much easier and better way of going about it. I am also not sure if this is necessary as surely the results seem to be in an array when gathered from the SQL database but i am unsure if this array is populated with each while loop or stored and can be accessed at any point
If any one can give me an example of something similar or point me at some documentation much appreciated
Try this:
$count = 0;
while ($row = mysqli_fetch_array($result)) {
$send[$count] = array($row['Name'], $row['Email'], $row['Mobile']);
$count++;
}
I have a better way for you. You could also use the id for your index, if you have one:
while ($row = mysqli_fetch_array($result)) {
$send[$row['id']] = array(
"Name" => $row['Name'],
"Email" => $row['Email'],
"Mobile" => $row['Mobile']
);
}
You can use:
$count = 0;
while($row = mysqli_fetch_array($result))
{
$send[$count] = $row;
$count ++;
}
Also you might want to use the table id as an array index, so you can access the records by ID later. In that case you can do:
while($row = mysqli_fetch_array($result))
{
$send[$row['id']] = $row;
}
You're declaring your array inside your loop. So it will reset it every time.
$send = array();
while($row = mysqli_fetch_array($result))
{
$send[] = array($row['Name'],$row['Email'],$row['Mobile']);
}

How do I insert values into an multidimensional-array, then show them?

I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!
Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.
$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>

PHP/MySQL: How to get multiple values from a PHP database method

Sorry for the incredibly newbie question, but I can see myself drifting into bad practices if I don't ask.
I have a PHP method that I want to return all the values of a given database column, in order to place the contents in a dropdown menu for a HTML form. I could obviously construct the whole HTML in the PHP method and return that as a string, but I imagine this is pretty bad practice.
Since PHP methods can only return one value, I imagine I'll need to call the method several times to populate the dropdown menu, or pass an array from the method.
What would be a good solution to this (presumably) common problem? Thanks.
Well, an array is one value, containing tons of other values. So just have your method return a array of results.
edit: as Hammerstein points out you could use objects but its as good/bad as arrays depending on context. Very similar.
You could use an object as your return type. So;
class MyReturnValue
{
public $Value1;
public $Value2;
}
function getMyValues()
{
$results = GetDatabaseValues( ); // Assume this returns an associative array
$result = new MyReturnValue();
$result.Value1 = $results["Value1"];
$result.Value2 = $results["Value2"];
}
Then in your code, you can refer to $result.Value1 etc.
There is no PHP function to do this, so you will have to form an array from the results.
$column = array()
$query = mysql_query("SELECT * FROM table ORDER BY id ASC");
while($row = mysql_fetch_array($query)){
$column[] = $row[$key]
}
Then pass $column to your view(HTML)
foreach($column as $value)
{
echo "<li>" . $value . "</li>";
}
You can have arrays in arrays, so if you have a table with several columns you could assign them to an array as separate arrays:
$all_results = array();
foreach($rowInDatabase as $key => $value){
// each row will be an array with a key of column name and value of column content depending how you get the data from the DB.
$colname = $key;
$colVal = $value; //this is an array
$all_results[$colname] = $colVal; //append the current row to the array
}
}
code like this will populate your array with an array per row of the table so if there are ten rows and five columns you could get row 2 column 3 with $all_results[1][2]; (as they start from 0).
Not quite sure I understand what you want to do fully, but you could always pass the result back from the method, and then loop through it in your HTML.
Your method would be something like:
public function my_method()
{
$result = $db->query($sql_here);
return $result;
}
And then your HTML would be
<select>
<?
$result = $class->my_method();
while($row = $result->fetch_assoc())
{
echo '<option>'.$row['some_col'].'</option>';
}
?>
</select>

PHP: Unexpected behavior: foreach... {$array['country'][] = $value['country']}

Why does the operator
$array['country'][] return what logically would be $array[]['country']?
What I am saying is this. If you want to extract from a MySQL array, the value of ['country'] for every row, [1],[2]...[n], you have to use
$array['country'][]
despite fact that they are ordered as
$array['row#']['country']
Is this because PHP is reading something backwards, or because I am just lacking some fundamental array information?
FULL-ish code here
$result = array();
foreach($data as $value){
$array['country'][] = $value['country'];
$array['report'][] = $value['report'];
}
$data = $array;
Let me know if I am just dumb... I can't really grasp why this is working this way.
get an id from the db
SELECT id,country,report from yourdb
while ($row = mysql_fetch_array($result)) {
$array['country'][$row['id']] = $row['country'];
$array['report'][$row['id']] = $row['report'];
}
create an id
SELECT country,report from yourdb
$i=0
while ($row = mysql_fetch_array($result)) {
$array['country'][$i] = $row['country'];
$array['report'][$i] = $row['report'];
$i++
}
Why does the operator
$array['country'][]
return what
logically would be
$array[]['country']?
It is because you are constructing the array in that way:
If you use $array['country'][] = $value['country'];, you are adding a new value to the sub-array which is part of the containing array under the country key. So it will be mapped to $array['country'][], you cannot expect otherwise.
If you want it to map to array[]['country'], then (using part of code from
#Lawrence's answer), you'd have to add the new values using explicit numerical indexes as the key:
SELECT country,report from yourdb
$i=0;
while ($row = mysql_fetch_array($result)) {
$array[$i]['country'][] = $row['country'];
$array[$i]['report'][] = $row['report'];
$i++;
}
Assuming that $data has been built by you using a loop like what you pasted in the comments (while($row=mysql_fetch_assoc($result)){$data[]=$row;}) then my answer would be because that's exactly what you asked PHP to do.
The notion $data[] = some-value-here means take that value and add it with to the end of $data array with an auto-generated key I just don't care. That is, PHP will basically see what the last item's key is, add 1 and use that as the key for the item you are adding to the array.
So what you are doing with that loop is building an array whose keys are numbers starting from 0 and incrementing (+1 each cycle, this is the [] effect) and using these keys for the rows you are getting off the database result set.
If you want to access $data in the way you described, then you have to change the way you are building it. See Lawrence Cherone's answer for that.

Categories