Creating multidimensional array containing database output - php

Im creating a website, where I make a foreach, that echos out some groups, containing checkboxes, with values and names. At the moment that data comes from a multidimensional array, but writing that array when adding new items, is slow, and not very user-friendly.
At the moment, my foreach looks like this:
echo '<form method="post" action="'.$_SERVER['PHP_SELF'].'">';
/* NEXT WE CREATE OUR FOREACH LOOPS TO ECHO THE HTML FOR LOOKS AND CHECKBOXES */
$totalID=0; // this is a counter we use to build our check box names
foreach ($items as $list){
$totalID++; // add one to the checkbox name counter
echo "<h2>{$list['title']}</h2>\n"; // and echo out our section header
foreach ($list['items'] as $cbox){ // now for each item in the list, call it $cbox
// $cbox now holds the item name, and point value
echo "<label class='checkbox'><input type='checkbox' name='totals[$totalID][]' value='{$cbox[1]}'> {$cbox[0]}</label>\n";
}
}
echo "</form>";
And my array I write is something like this:
$items['computers']['title']='Computer Brand';
$items['computers']['items'][]=array('Apple iMac',1);
$items['computers']['items'][]=array('Apple Macbook',.5);
$items['phones']['title']='Phone Brand';
$items['phones']['items'][]=array('iPhone',1);
$items['phones']['items'][]=array('HTC',1);
As said, I can write this, but takes time.
I want to get it into a database, that data above, but I'm having problems about echo'ing it out, I really can't see how I should do.
My current database looks like this:
http://i.stack.imgur.com/Rj0wQ.png
Anyone that have some tips how to do this easy, and also do it user friendly?
Thank you!

$sql = "SELECT category, title, brand, point FROM yourtable ORDER BY category, title";
$result = mysql_query($sql);
$data = array();
while(list($category, $title, $brand, $point) = mysql_fetch_array($result)) {
if (!isset($data[$category])) {
$data[$category] = array();
}
if (!isset($data[$category]['title'] && (!empty($title)) {
$data[$category]['title'] = $title;
}
if (!isset($data[$category]['items'])) {
$data[$category]['items'] = array();
}
$data[$category]['itemps'][] = array($brand, $point);
}
Your table is just screaming for some normalization, however. It's a horrendous construct.

Well if you dont' want to parse your result into a multi-dimensionnal array like you did before which would be the easiest task but you have to double de CPU work, there is one way i use often in this case:
No1: Make sure your result is sorted by "Category" and then sorted by whatever criteria you want to order your answers as.
No2: Initialize the "$current_category" to NULL
No3: Loop and detect new $categories and output the header as you go. Your script will look like this:
$currentcategory = NULL;
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
//Check for a category change
if($currentcategory != $row['category']){
echo '<h2>'.$row['title'].'</h2>'.PHP_EOL;
$currentcategory = $row['category'];
}
//Output the label
echo '<label class="checkbox"><input type="checkbox" name="totals'.$row['id'].' value="'.$row['point']'."> '.$row['brand'].'</label>'.PHP_EOL;
}

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>";
}
}

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

PHP Nested Loop. How on the second loop print items according to the id of the first loop?

I need to print a wine list from a database.
I need to print at first a categorie and after all the items that are inside. Thats the order. And i have multiple categorie. So at the end the result will be categorie1, many items, categorie2 many items...
This is the code that i write from now: I think that my problem is to print items according to the id of the alcool_categorie !!
$q_vine = "SELECT * FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
$q_bouteille = "SELECT * FROM alcool_item where ALCNID = '$alid'";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
for($i = 0; $i < $n_vine; $i++){
echo mysql_result($r_vine,$i,'named').'<br/><br/>';
for($z = 0; $k < $n_bouteille; $k++){
echo mysql_result($r_bouteille,$k,'name').'<br/>';
}
}
I think it's best to use a "JOIN" in your query and then order the rows in the way you want them to be ordered, then you'll only need one loop. While running the loop you compare the category name with the previous category name and if it changes display the category name.
Example
$sql = "SELECT categoryName, bottleName FROM category INNER JOIN bottle ON category.categoryId = bottle.categoryId ORDER BY category.categoryId";
$result = mysql_query($sql,$connection);
$categoryName = ''; //just to make sure the first time the Category is named
while ($row = mysql_fetch_assoc($result)) {
if($categoryName != row['categoryName']){
$categoryName = row['categoryName'];
echo '<h1>'.$categoryName.'</h1>';
}
echo row['bottleName'].'<br/>';
}
Try this after correctly giving the category id field name in the query and inside the first while loop.
$q_vine = "SELECT id, named FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
while ($row = mysql_fetch_assoc($r_vine)) {
$categories[$row['id']] = $row;
}
$q_bouteille = "SELECT name, ALCNID FROM alcool_item ";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
while ($row = mysql_fetch_assoc($r_bouteille)) {
$items[$row['ALCNID']] = $row;
}
foreach ($categories as $category_id=>$category) {
echo "<ul><li>{$category['named']}<ul>";
foreach ($items[$category_id] as $item) {
echo "<li>{$item['name']}</li>";
}
echo "</ul></li></ul>";
}
You will want to look into PHP's foreach construct. Foreach loops through an entire array of results, for each element inside the array, it extracts its value and optionally also its key. This will not require the use of mysql_num_rows.
Instead of calling mysql_result, you could use mysql_fetch_assoc to get a row's value from your mysql_query. The row's To get all values, you can incorporate this into a loop even. If you do the latter, you can create your own array of key/value pairs and use this inside a foreach construct.
Also note that the use of mysql is outdated, you will want to use mysqli now, which is very similar to mysql.

Multiple for loops - how to print data

i want to make a website something like popurls.com, but I will use static data stored in MySQL database. Btw I use php/mysql.
In each list i want to show around 10 links (just like on popurls). In that case, if I would have 20 lists, i would need to make 20 'for' loops (for each particular list).
My question is; is there some better way to print that 20 lists instead of using 20 'for' loops in php.
a for loop or a foreach loop will work fine, but it will be a lot less coding if you just create a single for loop and push content into an array of arrays or an array of strings... you can then do whatever you'd like with the actual content (assuming we're grouping by a column category. I'll use an example that uses an array of strings (and the query that I reference is explained here: http://explainextended.com/2009/03/06/advanced-row-sampling/)
$query = mysql_query([QUERY THAT GETS ALL ITEMS, BUT LIMITS BY EACH CATEGORY]) or die(mysql_error());
$all_items = array();
while($row=mysql_fetch_array($query)){
if (!isset($all_items[$row['category']])){ //if it isn't created yet, make it an empty string
$all_items[$row['category']] = "";
}
$all_items[$row['category']] .= "<li><a href='".$row['url']."'>".$row['title]."</a></li>"; //concatinate the new item to this list
}
Now we have an array where the block of HTML for each section is stored in an array keyed by the name of the category. To output each block, just:
echo $all_items['category name'];
PHP's foreach http://php.net/manual/en/control-structures.foreach.php
Depends a lot on your data input but I could imagine something like this:
<?php
$lists = arrray('list1', 'list2', 'list3');
foreach ($lists as $current) {
$data = fetch_data_from_mysql($current);
foreach ($data as $link) {
echo "Link";
}
}
function fetch_data_from_mysql($current)
{
$list_data = array();
// do whatever is required to fetch the list data for item $current from MySQL
// and store the data in $list_data
return $list_data;
}
You just need two foreach loops. Assuming that you take the data from a mysql table (like you wrote), this could be like this:
$list_query = mysql_query("SELECT * FROM lists";)
while( $list = mysql_fetch_array($list_query) )
{
echo "<h1>{$list['title']}</h1>";
$query = mysql_query("SELECT * FROM entries WHERE list_id = {$list['id']}");
while( $entry = mysql_fetch_array($query) )
{
echo "- {$entry['name']}<br />";
}
}
You can get all the information from the database and parse it into an array, something like
array[<news type1>] = array( link1, link2, link3, etc);
array[<news type2>] = array( link1, link2, link3, etc);
and so on
and on the layout you can use
foreach ($newsCategory AS $categoryLinks) {
foreach ($categoryLinks AS $newsLink) {
<show the link and / or extra data>
}
}
Just store your links in two-dimensional array. That way you'll have to make 1 outer loop (iterating over lists) and 1 inner loop iterating over links in a particular list.
$links = array(
'science' => array('link1', 'link2', ...),
'sports' => array('link1', 'link2'),
// ... and so on
);
foreach ($links as $category => $urls) {
echo "Links in category: $category\n";
foreach ($urls as $url) {
echo $url . "\n";
}
}

Saving 2 variable's values for later use

I tried to make the title of this most the most descriptive as possible, as I don't know how to do this... I know the best way will be value storage in some form of array.
My question is this, I have this query where I need to pic the tag name and the correspondent id for a later comparison and use ($tag_nome is collected by $_GET):
$resultado2 = mysql_query("SELECT tag.tag_nome, rel_frasetag.id_tag
FROM tag, rel_frasetag
WHERE rel_frasetag.id_tag = tag.id_tag AND
rel_frasetag.id_frase='$id_frase'") or die(mysql_error());
while($res2 = mysql_fetch_array($resultado2))
{
$tag_nome2 = utf8_encode($res2['tag_nome']);
$id_tag = $res2['id_tag'];
}
I already tried some things like array_push() but couldn't get it to work.
At the end of this snippet I'm comparing $tag_nome2 against $tag_nome to see if they match. If so, it will echo one link with the corresponding $tag_nome2 and $id_tag, and if not will echo pretty much the same thing, with a different class on the link.
My best guess as far as what you want to do is the following:
if( $tag_nome2 == $id_tag )
{
// do something
}
else
{
// no match
}
Perhaps though, you're saying your variable names are being overwritten? You're inside of a while loop, so the values they'll ultimately receive will be that of $res2[] at the end of the last iteration of your loop.
And if you're saying you want to save your rows for later, you can do:
$holder = array();
$res = mysql_query("");
while( $row = mysql_fetch_assoc($res) )
{
$holder[] = $row;
}
print_r($holder);

Categories