Grabbing key value from a mysql query - php

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.

Related

Having difficulties with php foreach and passing by reference

I'm pulling some data from a database (with a function I have called query), and I want to add another key/value pair to each result, i.e.:
$items = query("SELECT * FROM items");
foreach($items as &$item) {
$item['fixedname'] = str_replace(' ','_',$item['name']);
}
Now I want to put these on an html view, i.e.:
<?php foreach($items as $item): ?>
<div id="<?= $item['fixedname'] ?>" ><?= $item['name'] ?></div>
<?php endforeach; ?>
However, this doesn't output correctly. For instance, when the query returns two items, the loop in the php outputs the same thing twice. If there are three: it outputs the first one, then two of the second one. What's the problem here?
When modifying using foreach() I've had weird results on occasion. I use
foreach ($items as $key=>$value) {
$items[$key] = modified($value);
}
Or, why not do it in the SQL SELECT your, fields, here, REPLACE(name, ' ', '-') AS fixedname
The data returned on the right side of the foreach is a copy of the data, it can't be modified directly. Instead you need to fetch both the $key (the ID of the item in the array) and the $item. By letting PHP telling you the $key you don't need to worry about whether the array is normal (e.g. having indexes of 0,1,2,...) and associative.
This example would walk the $items array and add 'fixedname' into it.
foreach($items as $key => $item) {
$items[$key]['fixedname'] = str_replace(' ','_',$item['name']);
}
You could do a normal for loop
<?php
for($i=0; $i < count($items); $i++){
$items[$i]['fixedname'] = str_replace(' ','_',$items[$i]['name']);
}
?>
Then everything will be ready when you go to your next foreach.
u have bunch of wrong things
1- dont use mysql , use PDO or mysqli instead
2- $items = query("SELECT * .... --->Call to undefined function query()
change it to
$items = mysql_query("SELECT * ....
3- Invalid argument supplied for foreach() ,
you missed to fetch your query
try this whole code
$items = mysql_query("SELECT * FROM items");
?>
<?php while ($row = mysql_fetch_array($items) ) {?>
<div id="<?php echo $row['fixedname'] ;?>" ><?php echo $row['name']; ?></div>
<?php } ?>

Creating multidimensional array containing database output

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

How to retrieve and display an array with objects from php cell using a loop?

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

php json array problems

I am creating a json array in PHP like this (it's inside a class):
$STH = $DBH->query("SELECT ID,title,content FROM table WHERE ID= '".$ID."' ");
$querycount = $STH->rowCount();
if($querycount!=0):
$STH->setFetchMode(PDO::FETCH_OBJ);
while( $row = $STH->fetch()) :
$thread[$row->ID]['title'] = $row->title;
$thread[$row->ID]['content'] = $row->content;
endwhile;
$this->querycount = $querycount;
$this->thread = json_encode($thread);
else:
$this->querycount = $querycount;
endif;
But I seem to get "strange" decodes the other end. I cannot actually reference the array by key's;
So far it will let me do this: (Where af_threads is the class name and $key id the ID in the table query)
$threads = new af_threads($key,$DBH);
$threads = json_decode($threads->thread);
foreach($threads as $key1=>$thread):
foreach($thread as $key2=>$val):
echo $key2;
echo $val;
endforeach;
echo '<hr />';
endforeach;
But what it will not let me do is something like this
$threads[$key]['title']
I'm not sure why. As the class builds i.e. with more rows etc. I will need to call specific rows in specific places. i.e. $threads[$key]['newrow'], $threads[$key]['newrow2'], and or to manipulate a row with say substr(); etc.
Yes I know I could just echo out an array without json, but eventually I want to add cross domain functionality with JQuery getJSON() ...
Have I got it all wrong?
By default, json_decode() returns stdClass, modify second line with
$threads = json_decode($threads->thread, true)
and you will get an associative array and be able to reference it by keys, $threads[$key]['title'] for example.

How do I code a loop for my echo statement?

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

Categories