Loops and SQL in PHP - php

I've got the following code that I can't seem to get working:
function drawTable($result)
{
var_dump($result);
echo '<table border = "1" cellpadding="10">';
echo '<tr>
<th>Album</th>
<th>Tracks</th>
<th>Price</th>
<th>Purchase</th>
</tr>';
foreach($result as &$album) {
$albumID = $album['Album_ID'];
var_dump($albumID);
//echo '<tr><td><img src="' . $resultRow['Image_URL'] . '" width="200px" height="200px"> </td>';
$tracksQuery = "SELECT Track_Title FROM Track WHERE (Album_ID = '$albumID')";
var_dump($tracksQuery);
$DBConnector2 = new DBConnector();
$tracks = $DBConnector2->getSQL($tracksQuery);
var_dump($tracks);
while ($trackTitle = mysqli_fetch_array($tracks)) {
echo $trackTitle['Track_Title'] . '<br />';
}
}
echo '</table>';
}
The var $result is a list of Album_IDs. I want to iterate over this using a foreach and also to run a query to get its associated tracks.
The var_dump gives:
object(mysqli_result)#4 (0) { }
In addition, the SQL I'm using for $result is
SELECT *
FROM Album
ORDER BY Album.Album_Name ASC
Very basic. You can see the other SQL use in the loop.
What am I doing wrong? Thanks.

I assume that $result is the return of a mysql_query function. You can't do that as it is still a reference to a mysql resultset, not the real mysql result.
Instead of using the foreach iteration, use a while loop like the following:
while ($album = mysql_fetch_assoc($result)) {
...
...
}
I'm not so sure whether in the first place you may pass a mysql result reference in a function but you can give it a try :)

You cannot use foreach with mysqli, that I know of. Change it to this:
while ($row = $result->fetch_assoc()) { ...

Related

unable to generate multiple random words at a time using order by rand using php mysql

Hi friends am trying to produce random words using order by rand but unable to produce.Here is my code
for($i=0;$i< 10;$i++) {
$result = mysqli_query($conn,"SELECT * FROM questions ORDER BY RAND() LIMIT 2");
if (!$result) {
/*die('Invalid query: ' . mysql_error());*/
die("Query failed".mysqli_error());
}
while ($row = mysqli_fetch_array($result)) {
$meta_descriptions = '{' $row['fact'] . ' ' . '|' $row['fact'] . '|' . $row['fact']}';
echo $meta_descriptions;
}
}
My questions table has one column that is column fact. i t has three values like
apple
ball
cat
Am getting output as
ball |ball| ball only
I want it to be random like
ball|cat|apple
How can I generate it
See this statement inside your while() loop,
$meta_descriptions = '{' $row['fact'] . ' ' . $row['fact'] . '}';
You're using same column value two times in each iteration of while() loop. Simply change your while() code section in the following way,
$meta_descriptions = '';
while ($row = mysqli_fetch_array($result)) {
$meta_descriptions .= $row['fact'] . '|';
}
$meta_descriptions = rtrim($meta_descriptions, '|');
echo $meta_descriptions;
Alternative method:
Create an empty array in the beginning. In each iteration of while() loop, push $row['fact'] value to this array. And finally apply implode() function on this array to get the desired result.
So your code should be like this:
$meta_descriptions = array();
while ($row = mysqli_fetch_array($result)) {
$meta_descriptions[] = $row['fact'];
}
$meta_descriptions = implode('|', $meta_descriptions);
echo $meta_descriptions;
change inside your while loop.
$meta_descriptions = '{';
$descriptions = array();
while ($row = mysqli_fetch_array($result)) {
$descriptions[] = $row['fact'];
}
$meta_descriptions .= implode(" | ",descriptions);
$meta_descriptions .= '}';
echo $meta_descriptions;

while loop inside foreach loop returns only 1 row

I'm trying to output a table using php and ajax. Now my function gets data from 1 table and then iterate on the row of that table to get rows from different table and then form a table. To achieve this I have put while loop inside foreach loop, the data from the first table is in array, so Im iterating on array using forean and then putting while loop.
This results in only 1 row. Need help
public function GetReportData()
{
$status_list = $this->GetStatusList();
foreach ($status_list as $status)
{
$staus_orignal = $status->orignal_status;
$status_site = $status->site_status;
try
{
$db = $this->GetDBHandle();
$start_date = '05/01/2015';
$end_date = '05/02/2015';
$affiliate_id = 0;
$output_string = '';
$output_string .= '<table class="tg">
<tr>
<th class="tg-031e"><span style="color:#fff;">Disposition Type</span></th>
<th class="tg-yw4l"><span style="color:#fff;">Lead Count</span></th>
<th class="tg-yw4l"><span style="color:#fff;">Revenue</span></th>
</tr>';
$query = "exec affiliate_portal_report_data_select $staus_orignal, $affiliate_id,'". $start_date."','". $end_date."'";
$result = odbc_exec ( $db, $query );
if ( !$result )
{
throw new Exception ( 'Error from ' . $query . ': ' . odbc_errormsg() );
}
else
{
while ( odbc_fetch_row ( $result ) )
{
$lead_count = odbc_result( $result, 'leadcount' );
$revenue = odbc_result( $result, 'revenue' );
$output_string .= '<tr>
<td class="tg-yw4l">'.$status_site.'</td>
<td class="tg-yw4l">'.$lead_count.'</td>
<td class="tg-yw4l dollar">'.$revenue.'</td>
</tr>';
}
}
}
catch ( Exception $e )
{
$error_status = $e->getMessage();
print $error_status;
}
}
$output_string .= '</table>';
return $output_string;
}
There is an $output_string = ''; on line 16. You are re-initializing your output on each iteration of the foreach loop, so you will only ever get the last row.
I am not entirely sure from your question, but if this code is supposed to produce one table, then you can get rid of $output_string = ''; altogether, put this:
$output_string = '<table class="tg">
<tr>
<th class="tg-031e"><span style="color:#fff;">Disposition Type</span></th>
<th class="tg-yw4l"><span style="color:#fff;">Lead Count</span></th>
<th class="tg-yw4l"><span style="color:#fff;">Revenue</span></th>
</tr>';
before the foreach loop, and leave this:
$output_string .= '</table>';
after the foreach loop (like it already is).
But if your code is supposed to produce multiple tables, then you still need to get rid of $output_string = '';, and you can leave the <th> section where it is, but you'll need to move $output_string .= '</table>'; inside the foreach loop, or you will end up with a bunch of unclosed table tags.
As said by #Don'tPanic in comments, you have to initialise your $output_string variable outside of the loop.
Like actual, you are recreating an empty string for each row.
If you build an array or a string by looping another, keep in mind to make the variable declaration outside, and the incrementation inside the loop.
Change your code to :
$output_string = '';
foreach ($status_list as $status) {
// ...
$output_string .= 'yourstring';
// ...
}

How to collect functions results into one array and return this array?

My php function looks like that
function generateTour ($lang, $db)
{
echo '<table border="0" cellpadding="0" cellspacing="0" width="100%">';
$title='title_'.$lang;
$txt='txt_'.$lang;
$result = $db->query("SELECT id, $title, $txt FROM 1_table");
$count= $result->num_rows;
$i=1;
while($row=$result->fetch_object())
{
if($i%3==0) echo '<tr>';
echo '<td width="33%">
<div class="tour_item" style="background-image:url(core/content/img/pages/1/slide/'.$row->id.'.png)">
<div class="tour_item_title"><a href="?id='.$row->id.'">';
echo '</a></div><div class="tour_item_text"><a href="?id='.$row->id.'"></div>
</div>';
if($i==$count-1) echo '</td></tr>';
else if($i%3==0) echo '</td></tr><tr>';
$i++;
}
echo '</table>';
}
As you see it echoes result line by line. Not all at once. I want to collect all variables to one array and return this array. Is it possible? how to do it?
Please don't post your ideas about security holes .. etc. I'm filtering $title, $txt varibales against sql injections. (i have array for of possible field names. My filter function checks theese variables' values every time. )
$data = array();
while ($row = $result->fetchObject()) {
$data[] = $row;
}
Is the absolutely most basic method of cacheing a result set in an array. You'd just modify this to store your generated html instead.
Try this:
function generateTour ($lang, $db)
{
$output = '<table border="0" cellpadding="0" cellspacing="0" width="100%">';
$title='title_'.$lang;
$txt='txt_'.$lang;
$result = $db->query("SELECT id, $title, $txt FROM 1_table");
$count= $result->num_rows;
$i=1;
while($row=$result->fetch_object())
{
if($i%3==0)
{
$output .= '<tr>';
}
$output .= '<td width="33%">
<div class="tour_item" style="background-image:url(core/content/img/pages/1/slide/'.$row->id.'.png)">
<div class="tour_item_title"><a href="?id='.$row->id.'">
</a></div><div class="tour_item_text"><a href="?id='.$row->id.'"></div>
</div>';
if($i==$count-1)
{
$output .= '</td></tr>';
}
else if($i%3==0)
{
$output .= '</td></tr><tr>';
}
$i++;
}
$output .= '</table>';
return $output;
}
Edit:
Now it's easier to read the code. This solution put all content in one variable. You don't need a array.
You can use ob_start() and ob_get_clean() to buffer all output into a variable, then output that variable, like this:
ob_start();
print "Hello"; // Prints to buffer instead of screen
$out = ob_get_clean(); // Contains: Hello
echo $out; // Prints: Hello

While loop together with foreach

I'm really stuck trying to resolve what should be quite simple.
I Have this
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$id = array('33540116', '33541502');
foreach($id as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
So the code is decoding a json string then using foreach to echo each result.
This json file is rather large and I'm only interested in certain records that match the id's stored in a mysql table.
To do this I have replaced the id array string above with mysql select statement.
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$result = mysql_query("SELECT id FROM people");
$row = mysql_fetch_array($result);
$id = array($row['id']);
foreach($id as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
Although this works, it only gives me 1 result.
What I really need is to loop through the results.
Unfortunately I don't know how to construct a while loop together with foreach.
I will greatly appreciate your assistance.
UPDATE (extra question)
Thanks everyone. You have helped me solve the problem.
However, I have another question that relates to this matter.
I mentioned above that I merely wanted to echo the results.
But this isn't exactly true.
What I really want to do is update the same mysql table with the results retreived from the json file.
I have a table called people with fields id, name and age.
How can I update this table with these results?
Thanks again.
mysql_fetch_array only fetches one row at a time. You can use a while loop to continue fetching rows. The mysql_fetch_array function returns false once the whole result set has been fetched, so that will cause the while loop to terminate as desired.
Also, I removed the foreach loop on $ids. Since there will only be one element in the array it's unnecessary to put the code in a loop.
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$result = mysql_query("SELECT id FROM people");
while ( ( $row = mysql_fetch_array($result) ) ) {
$id = $row['id'];
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
Try this:
while($row = mysql_fetch_array($result)) {
$id = array($row['id']);
foreach($id as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
}
You are using this :
$row = mysql_fetch_array($result);
This will only fetch one row from the database.
If you want to fetch more than one row, you have to call mysql_fetch_array() in a loop :
while ($row = mysql_fetch_array($result)) {
// Work with the current row
}
In your case, you'd have something like this :
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
You do not need foreach loop the while is just enough
$result = mysql_query("SELECT id FROM people");
$id = array($row['id']);
while($row = mysql_fetch_array($result))
{
echo $json->$row['id']->person->{'name'}. '<br />';
echo $json->$row['id']->person->{'age'}. '<br />';
}
You have a couple of issues. Firstly, you shouldn't be using foreach($id as $id) since you are using the same variable for both. Instead it should be foreach($ids as $id). Secondly, you can get a list of the ids and echo out the correct json values as follows
<?php
$json = json_decode('{
"33540116":
{"person":
{"name":"John", "age":"36"}},
"33541502":
{"person":
{"name":"Jack", "age":"23"}}
}
');
$result = mysql_query("SELECT id FROM people");
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row['id'];
}
foreach($ids as $id) {
echo $json->$id->person->{'name'}. '<br />';
echo $json->$id->person->{'age'}. '<br />';
}
?>
Hopefully that will solve it

foreach data while inside?

Good afternoon, everybody. I have a doubt.
I have a WHILE, and accurate list of the data within it FOREACH . Does anyone know how to do this?
I would be very grateful for the help.
Example code.
$UserIDS= array();
$query->execute();
while ($lista = $query->fetch()){
$mensagem = $lista['mensagem'];
$UserIDS[] = $lista['idUser'];
echo
'
//Data from Forech, was shown here.
<div class="avatar"></div>
<div class="text">
'.utf8_encode($mensagem).'
</div>
';
}
//FOREACH data has to list before the $message, if put into the forech WHILE not sure of the fact that I have an array inside.
foreach ($UserIDS as $idUsua) {
echo "<div class='avatar'>".box::avatar($idUsua)."</div>";
}
Anyone know how do I pull data from FOREACH and put inside the in WHILE? be very grateful for the help.
Referring to my earlier answer to your other question:
// fetch all the data in one go
$query->execute();
$data = $query->fetchAll();
// and then iterate it
foreach ($data as $lista) {
echo "<div id='avatar'>" . box::avatar($lista['idUser']) . "</div>";
echo "<div class='text'>" . utf8_encode($lista['mensagem']). "</div>";
}
Your existing box::avatar call is then still free (as before) to make separate PDO query calls.
why don't you take this part
foreach ($UserIDS as $idUsua) {
echo "<div class='avatar'>".box::avatar($idUsua)."</div>";
}
into a function like
function userId($UserIDS){
$userAvatarDivs="";
foreach ($UserIDS as $idUsua) {
$userAvatarDivs.= "<div class='avatar'>".box::avatar($idUsua)."</div>";
}
return $userAvatarDivs;
}
and call it on
while ($lista = $query->fetch()){
$mensagem = $lista['mensagem'];
$UserIDS[] = $lista['idUser'];
echo
'
//Data from Forech, was shown here.
<div class="avatar"></div>
<div class="text">
'.utf8_encode($mensagem).'
</div>
'.userId($UserIDS);
}

Categories