I get only one printed result in the foreach echo loop at the bottom of the page.
<?php
defined('_JEXEC') or die('Restricted access');
$db =& JFactory::getDBO();
$query0 = "SELECT * FROM `jos_ginfo` WHERE . . . LIMIT 30";
//echo $query0;
$db->setQuery($query0);
$ginfo = $db->loadObjectList();
//echo
//$ginfo[0];
foreach($ginfo as $ginfo[$i]):
{$i=0; $i++;}
endforeach;
echo $db->getErrorMsg();
if(empty($ginfo)){
echo "<center>No
game found, try a different entry.</center>";
}else{
$pgndata = array ( $ginfo[$i]->Id);
$i=0;
foreach($pgndata as $ginfo[$i]->Id):
//I am only getting one printed result!
{
echo "<a href='/index.php?option=com_publishpgn&tactical-game=".$ginfo[$i]->Id."&Itemid=78.html'>\n";
echo "".$ginfo[$i]->White." v. ".$ginfo[$i]->Black." (".$ginfo[$i]->Result.") ".$ginfo[$i]->EventDate." ECO:".$ginfo[$i]->ECO."</a><br>\n";
$i++;
}
endforeach;
//echo "</div>";
}
?>
A few errors in your code:
foreach($ginfo as $ginfo[$i]):
{$i=0; $i++;}
On the first iteration, $i is undefined, so the first value pulled from $ginfo for the foreach loop will be stored in $ginfo[null]. You then set $i to 0, increment it, and loop around, so now the next value gets stored in $ginfo[1], as will all further iterations. So you end up with only two values extracted from the $ginfo object, and stored in the 'null' and '1' keys.
Later, you do
$pgndata = array ( $ginfo[$i]->Id);
You're not doing this inside a loop, so $pgndata becomes an array with a single element taken from $ginfo[1]->Id. You then immediately do
foreach($pgndata as $ginfo[$i]->Id):
but $pgndata has only a single element in it, which explains why you only have one item output.
I don't know what your ->loadObjectList() at the top does. Is it returning an array? An object? If it's any array, what's the point of the first foreach loop? You're destroying all but the first two values present in it.
It's never ever a good idea to try and modify an array WHILE you're looping over it in a foreach loop. It's kinda like trying to change a tire and axle and transmission on your car while going down the highway at 100mph. You might get lucky once, the rest of the time you're going to be spread into a thin ketchup stain.
Also, why are you mixing the {} and : / end syntaxes? Choose one or the other, but don't use both. Braces are standard and universally understood. the :/end version is far less popular and unfamiliar to most people.
I suppose, you need this:
$ginfo = $db->loadObjectList();
foreach($ginfo as $value)
{
echo $value . '<br />';
}
Further, see foreach manual and other loops.
$query = mysql_query("select * from table");
while ($result = mysql_fetch_array($query))
{
echo "$result[id]";
echo "$result[firstname]";
}
This is a modified version of Sarfraz's code.
Try this..
// Array of multiple games
$ginfo = $db->loadObjectList();
// Loop through games array
foreach ($ginfo as $index => $singleGameInfo)
{
foreach($singleGameInfo as $elementName => $elementValue)
{
echo "[$elementName \"$elementValue\"]\n";
}
}
In place of...
echo "[Event \"".$ginfo[0]->Event."\"]\n";
echo "[Site \"".$ginfo[0]->Site."\"]\n";
echo "[Date \"".$ginfo[0]->Date."\"]\n";
echo "[Round \"".$ginfo[0]->Round."\"]\n";
echo "[White \"".$ginfo[0]->White."\"]\n";
echo "[Black \"".$ginfo[0]->Black."\"]\n";
echo "[Result \"".$ginfo[0]->Result."\"]\n";
echo "[ECO \"".$ginfo[0]->ECO."\"]\n";
echo "[WhiteElo \"".$ginfo[0]->WhiteElo."\"]\n";
echo "[BlackElo \"".$ginfo[0]->BlackElo."\"]\n";
echo "[Annotator \"".$ginfo[0]->Annotator."\"]\n";
echo "[SetUp \"".$ginfo[0]->SetUp."\"]\n";
Edit: Are you trying to loop through multiple games or the field-data of a single game?
Edit2: Updated to loop through games
Related
I thought this was quite basic but for some reason I can't figure it out.
I have this query
$result = mysql_query("SELECT * FROM Users.Information LIMIT 0,1");
To grab the data (such as firstName, lastName), I use this snippet of code
<?php while ($row = mysql_fetch_assoc($result)): ?>
<?php foreach($row as $key=>$value) {
echo $value;
} ?>
<?php endwhile; ?>
which correctly prints everything I want.
Now in a separate table, I want to have it such that I will print the individual values separately. I thought this was quite simple like
first name:
however, this does not work. If I just do $value, of course this makes sense, but it prints the last value in the array.
How do I grab individual values? Do I just parse $value into different values, or is there an easier way?
Thank You.
$data = array() ; //Create a storage, so you can access it later.
<?php while ($row = mysql_fetch_assoc($result)): ?>
$data[] = $row ; //Add the value to storage.
<?php foreach($row as $key=>$value) {
echo $value;
} ?>
<?php endwhile; ?>
We are ready. We have $data array with all rows. Now you can manipulate it, access elements, pass somewhere.
$data[0] ; //Access the first element
echo $data[0]['FirstName'] ; //Print first name of the first row.
Here is my problem. I am returning results from a mysql database and using a for loop to echo the results. Though its getting a little complicated because I am using some table data to nest inside other results. This code returns "Pablo Picasso" inside a div called "Spain", fine, but if there is "El Greco" in Spain too, then I get two "Spain" divs, rather than just the one.
So: I'd like to only return a result once for each unique value in a table column, rather than for every one.
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[] = $row;
}
foreach ($results as $row)
{
echo "<div class=\"".$row['country']."\">".$row['country'];
echo "<div class=\"Box\">";
$tempCountry = $row['country'];
foreach ($results as $row)
{
if ($row['country']== $tempCountry) echo "<div>artists name</div>";
}
echo "</div>";echo "</div>";
}
I'm wondering if it is the construction of the nested loop, or something else, I don't know!!! Please help
I agree with #Kalpesh that you need to order the results by country.
Right now you have multiple nested loops when all you really should need is one. Try using just one loop to go through the data. On every iteration, check the $tempCountry value to see if it different compared to the current row's country. If it is, you need to close the current <div>, open a new <div> and update the $tempCountry value. Otherwise, echo the name of the artist.
EDIT: Psuedocode added below
Retrieve data from database (the query should sort the data by country)
Initialize $tempCountry to null
Loop over every row
If $tempCountry equals this row's country
Print the artist
Else
Set $tempCountry equal to this row's Country
Close the div tag
Open a new div tag
Print the artist
Note that you do not want to close the div tag on the first time through the loop. Also, you need to close the div tag after the loop finishes.
foreach ($results as $row) {
if ($tempCountry == $row['country']) {
echo "<div class=\"Box\">";
echo "<div>artist</div></div>";
}
else {
$tempCountry == $row['country'];
echo "</div><div class=\"".$row['country']."\">".$row['country'];
echo "<div class=\"Box\">";
echo "<div>artist</div></div>";
}
echo "</div>";
}
Create an empty array outside of your loop. On output push the values of $row into the array inside of your loop. Then only output if value does not already exist in the array. You can use in_array for this.
The solution I found was to nest a foreach inside another, the outer loop SELECTS with a GROUP BY.
In this example I get one outer for each country, then inside that , every person (or item) within that country (or with that column value). Really useful.
NEW CODE: SOLUTION (use GROUP BY to build outer container)
// create array to build group div
$country = mysql_query("SELECT * FROM table GROUP BY `country`");
// create array for inner contents
$result = mysql_query("SELECT * FROM table ORDER BY name");
//array for group(countries in this instance)
$countrys = array();
while ($row = mysql_fetch_assoc($country)) {
$countrys[] = $row;
}
//array for inner contents
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[] = $row;
}
$tempCountry="";
foreach ($countrys as $row)
{
$tempCountry = $row['country'];
echo "<div class=\"".$row['country']."\">";
echo $row['country'];
echo "<div class=\"Box\">";
foreach ($results as $row) {
if ($tempCountry == $row['country'])
{
echo"<div>inner contents of that group</div>";
}
}
echo "</div>";
echo "</div>";
}
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;
}
Currently, $selection outputs the following: MIN(Bale_ID), MIN(Incoming_Moisture) which is exactly what it should be outputting (they're names from another table). However, when I put $selection into the mysql_query $data1, it seems to just be reading the last value (MIN(Incoming_Moisture)) and only displays the results for that. How do I get the query to read the entire array of elements in $selection? Thank you!!
while ($row1 = mysql_fetch_array($fieldnames1)) {
$fields = $row1['fields1'];
$explode = explode(',',$fields);
if ($row1) {
for ($i=0; $i<$minrows; $i++) {
if ($i<$minrows-1){
$comma = ", ";
}
else {
$comma = "";
}
//$selection = "MIN(".$explode[$i].")".$comma;
//echo $selection;
$data1 = mysql_query("SELECT MIN(".$explode[$i].")".$comma." from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))");
$all1 = mysql_num_fields($data1); //return # of columns; for some reason is returning "1" right now.
while ($row2 = mysql_fetch_array($data1)) {
for ($col=0; $col<$all1; $col++) {
echo $all1;
echo "<td>Min: " . $row2[$col] . "</td>";
}
echo "</tr>";
}
}
}
}
echo "</table>";
Look at the order of operations in your code:
loop {
... fetch data ...
... assign results to $data1 ...
}
Nowhere in your loop do you output or save the results you've got in $data1, so each iteration of the loop overwrites the results of the previous iteration - in other words, only the LAST iteration's results will be stored.
you are running the query once per for loop cycle (1 field at a time) and since first ones yields in SQL error because of the trailin comma, these will not be echoed except the last one.
-- notice the error in first query
SELECT MIN(Bale_ID), from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))
SELECT MIN(Incoming_Moisture) from data WHERE (fchmitimestamp LIKE CONCAT(#year,'%',#month,'%',#day,'_________'))
use var_dump($selection) instead of echo $selection to see yourself
In a Flex project, I have an array with objects in it. I want to save this array in a cell on a mysql table along with some other basic info like title, and an id.
EDIT: just clarifying since i seem to be getting responses explaining how to echo all the rows... I'm trying to echo the contents of an array that was serialized and placed in a single cell. This array has objects in it.
So, I have this code here to serialize the array, and insert it along with the other info into my DB:
function submitLogDbObj($array,$id,$title)
{
$title=mysql_real_escape_string($title);
return mysql_query("INSERT INTO logs (text,id,title) VALUES ('".serialize($array)."','$id','$title')");
}
Then for a test i'm trying to make a loop that will display the log in a way that looks like a conversation...
an object in my array would look something like:
[1]
icon = ""
msg = "this is a test"
name = "Them: "
systemMsg = 0
[2]
icon = ""
msg = "yep it sure is"
name = "You: "
systemMsg = 0
So here's what i've got so far, but its not working! How can I make a loop that will take that array from the DB, unserialize it and then echo the convo in a way that looks like a chat log?
Thanks!
<?php
include_once("dbinfo.php");
$id= $_GET['id'];
$result = mysql_query("SELECT text,title FROM logs WHERE id='$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($result)
{
$log = unserialize($row['text']);
echo 'starting loop!';
echo "<ul>";
/* im not sure how to represent the length of an array in php thats why i just have $log.length */
for ($i = 1; $i <=$log.length; $i++)
{
echo "<div id='logbox'>";
echo "<li>";
$name=$log[$i]['name'];
$msg=$log[$i]['msg'];
echo "$name - $msg";
echo "</li>";
echo "</div>";
echo "<br />";
}
echo "</ul>";
echo 'finished loop!';
}
else
{
echo "Looks like this chat log has been deleted. Sorry!";
}
Well, there're a few things which could be better here:
The length of an array is found through count( $array ) or sizeof( $array )
$value . $otherValue means concatenate those two values. Since length is undefined in this context, $log.length means "$log.length".
The best way to loop through an array is foreach( $set as $val) or foreach( $set as $key => $val )
The preferred method of iterating through a SQL result is the while loop: while($row = mysql_fetch_array($result)){ or do... while (see below). Unless you specifically and consciously only want one, then it would be best to use that. And if you do only want one, then put a Limit in the query.
Serialized arrays in databases has a redundant flavor. Are you sure that this is what you want?
Your serialized array, before it is inserted, should also be run through mysql_real_escape_string.
br really shouldn't be needed if you're surrounding something in its own div.
Indent properly or the kitten of death will come for you.
The improved code:
$row = mysql_fetch_array($result);
// row could be empty if there were no results
if($row)
{
// we've already grabbed the first value, so we need
// to invert while into do... while.
do
{
$log = unserialize($row['text']);
echo "<ul>";
foreach( $log as $line )
{
// Are you sure this should be outside of the li?
echo "<div id='logbox'>";
echo "<li>";
$name=$line['name'];
$msg=$line['msg'];
echo "$name - $msg";
echo "</li>";
echo "</div>";
}
echo "</ul>";
}
while( $row = mysql_fetch_array($result) );
echo 'finished loop!';
}
else
{
echo "Looks like this chat log has been deleted. Sorry!";
}
Firstly, get into the habit of indenting your code properly, it will save you a lot of frustration when looking for errors.
You don't need to know the length of the array, you can just use a while loop: (coding from the hip here so let me know if you get errors)
$result = mysql_query("......") or die("Query failed");
//Keep going while $row isn't FALSE
//mysql_fetch_array returns false when there are no more rows
while($row = mysql_fetch_array($result)){
//You can close PHP tags here and insert the
//variables in the HTML, it often looks neater
//and your editor can colour code HTML, helping
//you to find problems
?>
<div>
<li><?php echo $row['name'] ?></li>
<li><?php echo $row['msg'] ?></li>
</div>
<?php
}
See the "fetch array while loop" of this tutorial for more examples.
$result = mysql_query("SELECT text,title FROM logs WHERE id='$id'")
echo "<ul>";
while ($row = mysql_fetch_assoc($results)) {
$name = $row['name'];
$msg = $row['msg'];
//display data how ever you want
}
echo "</ul>";