Reorder array from mysql query - php

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.

Related

'Grouping' PHP results from an MySQL query

I'm having difficulty achieving this one, so thought I'd ask..
I have a table which contains some field names. Each field entry in the table has a type, a name and an ID as per the norm.
I'd like to be able to group my SQL results so that I can 'print' each type (and the type's associated members) into a table. I tried the following:
$query = "SELECT id,type,opt_name FROM fields ORDER BY type";
$resource = $pdo->query($query);
$results = array();
while ( $row = $resource->fetch() ) {
$type[$row['type']] = $row['opt_name'];
$o_id = clean($row['id'], 'text');
$o_name = clean($row['opt_name'], 'text');
}
foreach ($type AS $o_type => $o_name) {
echo $o_type;
echo "<br>";
foreach (($type) AS $opt_name) {
echo $opt_name;
echo "<br>";
}
}
Please try not to worry too much about the HTML output, it's just for this example to show context.
When the code is executed, it will only print one row. As a result, I have 'print_r' tested both:
$type[$row['type']] = $row['opt_name'];
Which does indeed show only one row in the array. Creating:
$results = $row;
Shows all the data, but too much of it and not in the way I think will work with the 'foreach'.
I'm probably making a rookie mistake here, but can't see it.
Help!
You're going to be overwriting the value of $type['type'] instead of pushing more values onto it with:
$type[$row['type']] = $row['opt_name'];
You most likely want
$type[$row['type']][] = $row['opt_name'];
Then you'll need to fix your loop so you loop through the options, not the types twice.
foreach ($type AS $o_type => $options) {
echo $o_type;
echo "<br>";
foreach ($options AS $opt_name) {
echo $opt_name;
echo "<br>";
}
}

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>

Working with arrays in Kohana, Blank page?

tl;dr - Pushing an array (by $array[] or $array[$id] is not working in Kohana 3, it gives a blank white page.
I'm using Kohana (3), it's my first experience with MVC and it's been great so far; however, I'm working with a database and encountered a weird problem that I was hoping someone could shed some light on:
My workflow is like this, to give you an idea of my problems surrounding:
$sql = "SELECT table1.row1, max(table2.row1) as `maxAwesome` FROM table1, table2 WHERE table1.id=table2.table1id GROUP BY table1.id";
$table1Results = DB::query(Database::SELECT, $sql)->execute();
$masterArray = array();
foreach ($table1Results as $result1)
{
$sql = "SELECT * FROM table2 WHERE table2id='" . $result1['id'] . "' AND column > 21";
$table2Results = DB::query(Database::SELECT, $sql)->execute();
$subArray = array();
foreach ($table2Results as $result2)
{
$subArray[$result1['id']] = $result2;
// Even had just $subArray[] = array("whatever");
}
$masterArray[] = array("table1Data" => array(), "table2Data"=> $subArray);
}
I do a query where I run a couple max/min functions then do a query within the foreach doing another select to build a master array of data formatted the way I want it and all the SQL etc works fine and dandy; however, the problem arises when I'm pushing the array.
It seems whenever I push the array by doing either $array[] = array("data"); or by specifying the key $array[$id] = array("data"); Kohana gives me a straight blank page, no error, no output etc.
Sometimes I get a Kohana error indicating the key does not exist (duh, I'm creating it) but for the most part the output is straight white.
Why is this happening? Am I going about it wrong?
Thanks in advance.
Clarity edit:
My SQL blunders aside, the issue lies in the building of the secondary array, for example:
$queryStores = "SELECT stores.store_id, stores.title, max(product.discount) as `max_discount`, min(product.discount) as `min_discount`
FROM stores, products
WHERE products.store=stores.store_id
GROUP BY products.store";
$stores = DB::Query(Database::SELECT, $queryStores)->execute();
$formattedStores = array();
if (count($stores))
{
foreach ($stores as $store)
{
$formattedStores[$store['store_id']] = array(
"title" => $store['title'],
);
// Same result if just doing $formattedStores[] = array();
// Problem goes away should I do:
// $formattedStores = array("This works");
//
}
}
echo "<pre>";
print_r($formattedStores);
echo "</pre>";
That does not print an array, it simply gives a blank page; however, if i change it to just re-set the $formattedStores array to something I get an output. What is it about pushing the array that's causing a problem, perhaps a Kohana bug?
Thanks
Your code should be like:-
$sql = "SELECT table1.id, table1.row1, max(table2.row1) as `maxAwesome`
FROM table1, table2
WHERE table1.id = table2.table1id
GROUP BY table1.id";
$table1Results = DB::query(Database::SELECT, $sql)->execute();
$masterArray = array();
if (count($table1Results))
{
foreach ($table1Results as $result1)
{
$sqlInner = "SELECT * FROM table2
WHERE table2id = '" . $result1['id'] . "'
AND column > 21";
$table2Results = DB::query(Database::SELECT, $sqlInner)->execute();
$subArray = array();
if (count($table2Results))
{
foreach ($table2Results as $result2)
{
$subArray[$result1['id']] = $result2;
// Even had just $subArray[] = array("whatever");
}
}
$masterArray[] = array("table1Data" => array(), "table2Data"=> $subArray);
}
}
Some valuable coding standards & miss-ups:-
You have got the "id" field (w.r.t. the "table1" DB table) missing from the first SQL.
The second SQL should be better written using another variable naming, so as to keep it separate from the first one. Hence the second variable is named as "$sqlInner".
It's always better to check for any existence of array elements in an array variable, so I have used the simple checks using the "if" statement.
Hope it helps.
I've determined this to be memory related.

MultiDimensional Arrays

In Codeigniter, I have the following model
function get_item_history($id)
{
//from metadata_history get item_id and corresponding metadata
$this->db->from('metadata_history')->where(array('id'=>$id, 'current_revision'=> "TRUE"));
$query = $this->db->get();
$result = $query->result_array(); //store this in an array
// loop through the array
foreach( $result as $key => $row )
{
$array = array('item_id'=>$row['item_id'], 'current_revision'=> "TRUE");
$this->db->from('history')->where($array);
$query = $this->db->get();
$row['items'] = $query->result_array(); //
$result[$key] = $row;
}
return $result;
}
The problem is that this results in multiple queries to the SQL table increasing the execution time significantly (pagination is not an option)
I want to be able to pass the first query results to the second query as an array, so that I would have only a single go at the database, then rebuild an array from the results.
How should I rewrite this code (the second part)? Will it be faster (I suppose so)?
EDIT
Rebuilding the array from the results is what is flummoxing me.
http://www.phpbuilder.com/board/showthread.php?t=10373847
this is what I probably want, but am failing the jump
You can use inner query here. It is ideal situation for that -
function get_item_history($id)
{
// Here the above requirement can be achieved in a single query.
$sql = "select * from history h
where h.item_id IN (select item_id from metadata_history mh where mh.id = $id
AND mh.current_revision = TRUE) AND h.current_revision = TRUE";
$result = $this->db->query($sql);
//Return whichever column of result you want to return or process result if you want.
$result;
}
You should use JOINs to do this. It'll offload the execution of the query to the server. I can't give you too much more detail without knowing how your database is structured, but check out the docs on JOINs:
http://dev.mysql.com/doc/refman/5.0/en/join.html
http://www.webdesign.org/web-programming/php/mysql-join-tutorial.14876.html
http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php
Another option would be to do your wheres in the loop and move the query executation outside of the foreach:
// loop through the array
foreach( $result as $key => $row )
{
$array = array('item_id'=>$row['item_id'], 'current_revision'=> "TRUE");
$this->db->or_where($array);
}
$query = $this->db->get();
$row['items'] = $query->result_array(); //
$result[$key] = $row;
OK this took some work, and I also had to do some adjustments in my view
So the problem can be broken down into two main components
1) Pass the results of the first query as an array to the second one using where_in
2) Reorder/regroup the results of the first array by item_id
My earlier code was doing the second component implicitly
So here is what I did (limits, offsets, ordering have been cut out to improve readablity)
function get_item_history($id)
{
//from metadata_history get item_id and corresponding metadata
$this->db->from('metadata_history')->where(array('id'=>$id, 'current_revision'=> "TRUE"));
$query = $this->db->get();
$result_query1 = $query->result_array(); //store this in an array
foreach ($result_query1 as $key-> $row){
$result[$row['item_id']]['meta_info'] = $row; //the first query contains meta info, that must be passed to the view
$selected_id_array[] = $row['item_id']; //Create a array to pass on to the next query
$result[$row['item_id']]['items'] = array(); //declare an array which will hold the results of second query later
}
$this->db->select('h.*');
$this->db->from('history h');
$this->db->where_in('h.item_id', $selected_id_array);
$this->db->where(array('h.current_revision' => 'TRUE'));
$query = $this->db->get();
$row = $query->result_array();
foreach ($row as $key => $datarow) {
$result[$datarow['item_id']]['items'][] = $datarow; //populate the array we declared earlier with results from second query
}
return $result; // Now this variable holds an array which is indexed by item id and contains the results of second query 'grouped' by item_id
}
So the number of queries have been cut from ~10 to 2.
On my local machine this saves ~50 msec/page, though I am not sure how this will do for larger databases.

Categories