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>
Related
I need to be able to check if certain values are present in title_id, but as title_id's are index's it won't allow me to do this. Is there a way to store the values of the index without storing the array itself?
I have been searching for this answer for a long time but anything I search pulls up answers to different questions.
$selects = (array) null;
$res = mysqli_query($datab, "SELECT title_id FROM selects") or die($datab->error);
while ($datab = mysqli_fetch_assoc($res)) {
$selects[] = $datab;
}
///////////// part of a later query
if (!in_array($thisid, $selects)) {
$title[] = $datab;
$j++;
}
$selects is array of arrays, not array of title_id.
Try something like that:
while ($datab = mysqli_fetch_assoc($res)) {
$selects[] = $datab['title_id'];
}
I have an array returned from MYSQL query with 2 LEFT JOINs.
Question is: "Is there another way for writing the code below?". I got the code but I want a more clear way of it just to understand what happens inthere.
CODE:
$result = array();
while ($resultArr = mysqli_fetch_assoc($booksAndAuthors)) {
$result[$resultArr['book_id']] ['book_name'] = $resultArr['book_title'];
$result[$resultArr['book_id']] ['author'][] = $resultArr['author_name'];
print_r($result);
}
With the extract() function you can make the data in the result into variables. I have put the example below inside a function, so they will be local variables.
function getBooksAndAuthors($queryResult)
{
while ($data = mysqli_fetch_assoc($queryResult))
{
extract($data);
$BooksAndAuthors[$book_id] = array('book_name' => $book_title,
'author' => $author_name);
}
return $BooksAndAuthors;
}
This makes the code a lot more readable. You will, of course, have to know which columns there are in your database table. I also left out the extra '[]' for the author.
Here's how I recommend writing it, because I don't think you should depend on automatic creation of intermediate arrays.
$result = array();
while ($row = mysqli_fetch_assoc($booksAndAuthors) {
$bookid = $row['book_id'];
if (!isset($result[$bookid])) {
# First time we see this book, create a result for it
$result[$bookid] = array('book_name' => $row['book_title'],
'author' => array());
}
# add this author to the result entry for the book
$result[$bookid]['author'][] = $row['author_name'];
}
It's essentially equivalent, but I think it also makes the logic clearer.
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.
?>
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'];
}
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.