how to include previous generated WHILE content in an output template - php

I'm generating dynamic content from a database like this:
$sql_select_items = $db->query("SELECT * FROM table WHERE ...);
Then it pulls the results, which may be one or multiple, like this:
while ($item_details = $db->fetch_array($sql_select_items))
{
$items_content =
'<table><tr> '.
'<td>RETRIEVED CONTENT HERE</td> '.
'</tr></table>';
}
Then, further down, I am outputting the generated content like this:
if ($section == 'summary_main')
{
$summary_page_content['content'] =
$summary_page_content['details'] .
$items_content .
$summary_page_content['messaging_received'] .
$summary_page_content['footer']
;
$template->set('members_area_page_content', $summary_page_content['content']);
}
Everything works except for the content generated by $items_content , which only displays 1 item no matter if there are 1 or 20. I tried to do a
$items_content . =
instead of
$items_content =
but that didn't seem to work either and just gave me an error.
What am I doing wrong?

It's not $db->fetch_array($sql_select_items) it's $sql_selected_items->fetch_array(). Here's how I would do it:
$table_rows = $db->query("SELECT * FROM table WHERE ...");
if($table_rows->num_rows > 0){
$table = '<table><tbody>';
while($row = $table_rows->fetch_object()){
$table .= "<tr><th>{$row->title_column_name}</th><td>{$row->other_column_name}</td></tr>";
}
$table .= '</tbody></table>';
}
else{
$table = '';
// no results
}
echo $table;
$table_rows->free(); $db->close();

Outside of (before) the while loop:
$items_content = '';
Inside the while loop:
$items_content .= '...';
This will make sure that your $items_content variable exists before your loop, and then the .= will concatenate your string to the end of $items_content.
"What am I doing wrong?"
As you didn't post the error, I can only assume you either got an undefined variable notice, which is solved by placing $items_content = ''; before the loop, or your got a syntax error because the operator you should be using is .= and not . = (note that the space is wrong).

Related

Output data of JSON Array as HTML

I'm trying to create an overlay for my twitch stream, which display not only the recent follower but a certain amount of them in chronological order.
Here a visual representation:
(Styling is done with HTML/CSS)
I've already managed to get the JSON but I don't know how to echo the names for each ['follows']['user']['display_name']
This is the API:
https://api.twitch.tv/kraken/channels/kazutode/follows?limit=5&offset=0&client_id=nht9j8w0u4xazpm1fdc2fmkrqvoici
Here's my code so far (It's not alot, basically nothing xD)
<?php
$clientID = "nht9j8w0u4xazpm1fdc2fmkrqvoici";
$channel = "kazutode";
$limit = 5;
$offset = 0;
$response = json_decode(file_get_contents('https://api.twitch.tv/kraken/channels/'.$channel.'/follows?limit='.$limit.'&offset='.$offset.'&client_id='.$clientID), true);
?>
I know, I know. I should use curl but I don't know how so I stick to json_decode.
Can someone teach me how to get the wanted data out of the ['follows'] array?
You need a foreach loop. Here is some PHP+HTML mixed to give you an idea:
$table = '';
$table .= '<table>';
foreach($response['follows'] as $entry) {
$table .= '<tr>';
$table .= '<td>'.$entry['created_at'].'</td>';
$table .= '<td>'.$entry['user']['display_name'].'</td>';
$table .= '<td><a class="your-custom-class" href="'.$entry['_links']['self'].'">View channel</a></td>';
$table .= '</tr>';
}
$table .= '</table>';
echo $table;

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;

PHP converting JSON file into excel table is formatted incorrectly

I have made a PHP file that takes this JSON-based file: http://www.yellowpages.com.iq/ajax/get/register/Categories.php
and converts it into an excel-formatted-table with the formatting of (.cvs) using this code :
$contents = file_get_contents('http://www.yellowpages.com.iq/ajax/get/register/Categories.php');
$data = JSON_decode($contents);
$excel_file = fopen("file.csv", "a+");
$table = "<table border='1'>";
foreach($data as $elem) {
$table .= "<tr>";
foreach($elem as $key => $prop) {
$table .= "<th>$key</th>";
$table .= "<td>$prop</td>";
fwrite($excel_file, "$key,$prop\n");
}
$table .= "</tr>";
}
$table .= "</table>";
echo $table;
But the problem being, is it takes the data and displays it correctly, although it tends to format it like so: id 1
category Advertising
id 2
category Agriculture & FoodÂ
id 3
category Air condition
id 4
category Airlines
id 5
Aluminium & Glass
Instead of what I'm trying to make it look like which I made manually:
Any help would be appreciated!
You could change the code using fputcsv, which takes care of double quotes and escaping them.
For that you need to get the JSON as an associative array (provide the second argument true):
$data = JSON_decode($contents, true);
And then the loop you have would be replaced with this:
// "loop" for the header (only 1 iteration)
foreach($data as $elem) {
$table .= "<tr><th>" . implode("</th><th>", array_keys($elem)) . "</th></tr>";
fputcsv($excel_file, array_keys($elem));
break; // only need one row for header
}
// Restart loop for the data
foreach($data as $elem) {
$table .= "<tr><td>" . implode("</td><td>", $elem) . "</td></tr>";
fputcsv($excel_file, $elem);
}

No data shown when using correct query

I got a small for each loop that I want to test. But it only shows me two empty list items. I also tested the SQL in phpmyadmin and it returns a correct table. I want to show the title from that table but like I said, I am getting two empty list items.
Does anybody know what I am doing wrong?
<?
// content
$content = "SELECT * FROM `snm_content` WHERE catid = 13";
$contentcon = $conn->query($content);
$contentcr = array();
while ($contentcr[] = $contentcon->fetch_array());
foreach($contentcr as $content)
{
$contentje .= '<li>'.$contentcr['title'].'</li>';
}
echo $contentje;
?>
Replace $contentcr by $content inside the foreach loop.
<?
// content
$content = "SELECT * FROM `snm_content` WHERE catid = 13";
$contentcon = $conn->query($content);
$contentcr = array();
while ($contentcr[] = $contentcon->fetch_array());
foreach($contentcr as $content)
{
$contentje .= '<li>'.$content['title'].'</li>'; // Here
}
echo $contentje;
?>
Try this:
while ($contentcr = $contentcon->fetch_array()) {
$contentje .= '<li>'.$contentcr['title'].'</li>';
}
echo $contentje;
Remove foreach use only while
while ($contentcr = $contentcon->fetch_array());{
$contentje .= '<li>'.$contentcr['title'].'</li>';
}

Make A HTML/PHP Link

I have the code below:
$result = mysql_query("SELECT link, notes FROM links WHERE username='will';");
$html .= "<ul>";
while ($row = mysql_fetch_array($result)) { //loop
extract($row);
$html .= "<li>{$link} - {$notes}</li>";
}
I need the bit where it says {$link} to become a clickable link which opens a new window. How would I do this?
When I put tags around it you get this error:
The error is: Parse error: syntax error, unexpected '{' in /data/www/vhosts/themacsplash.com/httpdocs/ClipBoy/will.php on line 18
Line 18 is $html .= "<li>{$link} - {$notes}</li>";
In general you make a link like this: link title. So in your case like this:
$html .= "<li>{$link} - {$notes}</li>";
First create a correct code and make error handeling, than set variables outside quotes.
$qry = "SELECT link, notes FROM links WHERE username='will'";
$mysqlqry = mysql_query($qry);
if($mysqlqry){
if(mysql_num_rows($mysqlqry) > 0){
$html .= "<ul>";
while($row = mysql_fetch_array($result)) { //loop
extract($row);
$html .= "<li>". $notes ."</li>";
}
}
}
if your $link contains an url in the form "http://www.example.com/", use this:
$html .= "<li>{$notes}</li>";

Categories