PHP While Loop/Foreach Loops - php

I have a question on a different way to wright this code because its not doing what I want it to do..
I am creating a forum list that will display the section under that category. Well this is the issue as you can see that I have an If () {}Else {} statement that is being used to put the information in that list I want. The problem is that I need to add a special class to the last section under that category that will be called last-tr. Now my issue that I have is all the information is making it to the screen but the class is only applied to the last row and now the last row of all the category's which is what i'm looking for.
So something like this,
Welcome Center
Introduce Yourself
Say Hello To our Admins (last-tr)
Game
COD
BF4 (last-tr)
Code
PHP
Java
PDO (last-tr)
but what my code is giving me is
Welcome Center
Introduce Yourself
Say Hello To our Admins
Game
COD
BF4
Code
PHP
Java
PDO (last-tr) <- Just that one.
Here is the code
<?php
include '../../core/init.php';
include '../../includes/head.php';
//Getting Categories under Welcome
$db = DB::getInstance();
$user = New User();
$forum = New Forum();
$list = '';
$category = $db->query('SELECT * FROM forum_categories');
foreach ($category->results() as $category) {
$list .= '<thead>';
$list .= '<tr>';
$list .= '<th class="titles">' . $category->title . '</th>';
$list .= '<th>Last Post</th>';
$list .= '<th>Topics</th>';
$list .= '<th>Replies</th>';
$list .= '</tr>';
$list .= '</thead>';
$list .= '<tbody>';
$sections = $db->query("SELECT * FROM forum_section WHERE category_id = '$category->id'");
foreach ($sections->results() as $section) {
$x = 0;
if ($x < $sections->count()) {
$list .= '<tr>';
$list .= '<td>';
$list .= '<a href="/category.php?id='. $section->id .'">';
$list .= '<img scr="/images/icons/iconmonstr/intro.png">';
$list .= '</a>';
$list .= '' . $section->title . '';
$list .= '<span>' . $section->desc . '</span>';
$list .= '</td>';
$list .= '<td> Nasty </td>';
$list .= '<td> 0 </td>';
$list .= '<td> 0 </td>';
$list .= '</tr>';
$x++;
}else {
$list .= '<tr class="last-tr">';
$list .= '<td>';
$list .= '' . $section->title . '';
$list .= '</td>';
$list .= '<td> Nasty </td>';
$list .= '<td> 0 </td>';
$list .= '<td> 0 </td>';
$list .= '</tr>';
}
}
$list .= '</tbody>';
}
?>
<link rel="stylesheet" href="/css/fourms.css">
<title>Forums</title>
</head>
<body>
<?php include '../../includes/header.php'; ?>
<section id="main_section">
<section id="main_content">
<div id="forum-section">
<table class="forumlist">
<?php echo $list; ?>
</table>
</div>
</section>
</section>
<?php include('../../includes/footer.php'); ?>

Your if-statement should be if ($x < $sections->count()-1) because the last index of an array is always count-1 due to starting at 0.
OR
You could also fix it here by starting $x at 1, since you are using a foreach with the counter on the side, so its not like you'll get an out of index error. In other words:
foreach ($sections->results() as $section) {
$x = 1;
if ($x < $sections->count()) {
...
$x++;
}else {
...
}
}
But going with the first option is probably more straight-forward.

You are testing against your overall class not the data within the class.
$sections->count() is counting all of the sections not the entries in teh one section you are dealing with.
You need to test the count of the singular section
So if you had
$sectionsAll = array(
sectionOne = array( 1, 2, 3),
sectionTwo = array( 1, 2, 3),
sectionThree = array( 1, 2, 3)
);
You are currently testing on $sectionsAll, you need to check against sectionOne, sectionTwo, sectionThree

Related

How do you use a JSON API in PHP on Wordpress?

Here my url address for https://goalserve.com/getfeed/mytoken/topscorers/1204?json=1
How can I get the "player" data, I want to use make "top scorers standing widget" on my PHP Wordpress site.
{
"?xml":{
"#version":"1.0",
"#encoding":"utf-8"
},
"topscorers":{
"#sport":"soccer",
"tournament":{
"#name":"Premier League",
"#stage_id":"12041081",
"#gid":"1204",
"#is_current":"True",
"#id":"1204",
"player":[
{
"#pos":"1",
"#name":"Mohamed Salah",
"#team":"Liverpool",
"#team_id":"9249",
"#goals":"15",
"#penalty_goals":"2",
"#id":"138653"
},
{
"#pos":"2",
"#name":"Diogo Jota",
"#team":"Liverpool",
"#team_id":"9249",
"#goals":"10",
"#penalty_goals":"0",
"#id":"374031"
},
{
"#pos":"3",
"#name":"J. Vardy",
"#team":"Leicester City",
"#team_id":"9240",
"#goals":"9",
"#penalty_goals":"0",
"#id":"159732"
}
]
}
}
}
Answer
https://www.php.net/manual/en/function.json-decode.php
To do this you must first decode the json string into a php object. Then you must drill down to the proper data that you want. You can do this with the -> operator like so:
$players = json_decode($raw_string)->{'topscorers'}->{'tournament'}->{'player'};
Note that you should save the result of the decoded json string if you plan on reusing the data. Don't decode it more than once.
After you have the players, you can then iterate over the data and do what you want with it. Here is a minimal example with your data so you can see it all working together.
Example
Dataset
<?php
$raw_string = '
{
"?xml":{
"#version":"1.0",
"#encoding":"utf-8"
},
"topscorers":{
"#sport":"soccer",
"tournament":{
"#name":"Premier League",
"#stage_id":"12041081",
"#gid":"1204",
"#is_current":"True",
"#id":"1204",
"player":[
{
"#pos":"1",
"#name":"Mohamed Salah",
"#team":"Liverpool",
"#team_id":"9249",
"#goals":"15",
"#penalty_goals":"2",
"#id":"138653"
},
{
"#pos":"2",
"#name":"Diogo Jota",
"#team":"Liverpool",
"#team_id":"9249",
"#goals":"10",
"#penalty_goals":"0",
"#id":"374031"
},
{
"#pos":"3",
"#name":"J. Vardy",
"#team":"Leicester City",
"#team_id":"9240",
"#goals":"9",
"#penalty_goals":"0",
"#id":"159732"
}
]
}
}
}';
?>
Processing
<?php
$php_object = json_decode($raw_string);
$players = $php_object->{'topscorers'}->{'tournament'}->{'player'};
$html = '';
$html .= '<table>';
$html .= '<tr>';
$html .= '<td>Pos</td>';
$html .= '<td>Player</td>';
$html .= '<td>Team</td>';
$html .= '<td>Goals</td>';
$html .= '</tr>';
foreach ($players as $p) {
$html .= '<tr>';
$html .= '<td>' . $p->{'#pos'} . '</td>';
$html .= '<td>' . $p->{'#name'} . '</td>';
$html .= '<td>' . $p->{'#team'} . '</td>';
$html .= '<td>' . $p->{'#goals'} . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo($html);
?>
Output
<table><tr><td>Pos</td><td>Player</td><td>Team</td><td>Goals</td></tr><tr><td>1</td><td>Mohamed Salah</td><td>Liverpool</td><td>15</td></tr><tr><td>2</td><td>Diogo Jota</td><td>Liverpool</td><td>10</td></tr><tr><td>3</td><td>J. Vardy</td><td>Leicester City</td><td>9</td></tr></table>
Pos
Player
Team
Goals
1
Mohamed Salah
Liverpool
15
2
Diogo Jota
Liverpool
10
3
J. Vardy
Leicester City
9

Putting php arrays into html tags

I am trying to make a table that has different colors for each of its columns. There will be four columns.
$colors = array("background-color:red;", "background-color:gold", "background-color:pink;", "background-color:purple;");
$html = '<table>';
foreach( $array as $key=>$value){
$html .= '<tr style="background-color:white;">';
foreach($value as $key2=>$value2){
$html .= '<td>' . htmlspecialchars($value2) . '</td>';
}
$html .= '</tr>';
}
I created an array called colors that has the strings of the colors I want, but I don't know how to put that into the tag. I tried typing it in there, but since it is a string, it takes it as text instead of as code. Where it says "background-color:white;", I'd like it to call the values from the array instead. Thanks.
You can array_pop for this provided you have exactly 4 columns. You also can't apply background colours to <tr> like that, you need to apply them to the <td>
$colors = array("background-color:red;", "background-color:gold", "background-color:pink;", "background-color:purple;");
$html = '<table>';
foreach( $array as $key=>$value){
$color = array_pop($colors);
$html .= "<tr>";
foreach($value as $key2=>$value2){
$html .= "<td style='{$color}'>" . htmlspecialchars($value2) . '</td>';
}
$html .= '</tr>';
}

Multiple CheckBox delete

I am having a hard time on creating a multiple checkbox ajax delete. I am an ajax noob.
$sql = 'SELECT * FROM users';
$qry = mysql_query($sql);
$html = '';
$html .='<center>';
$html .= '+ Add New User';
$html .= ' || Delete User';
$html .= '<div id="div-data">';
$html .= '<table border="1" width="300px">';
$html .= '<tr>';
$html .= '<th width="5px"><input type="checkbox" id="cb-checkall"></th>'; //all
$html .= '<th> Users</th>';
//$html .= '<th>Delete</th>';
while($row = mysql_fetch_array($qry)) {
$html .= '<tr align="center">';
$html .= '<td><input type="checkbox" name="checkall" class="checkall" value="'.$row['uid'].'"/></td>';
$html .= '<td>'.$row['fname'].'</td>';
$html .= '</tr>';
}
$html .= '</table>';
$html .= '</div>';
echo $html;
delete.php (with the use of implode)
$deleteid = implode(",",$_POST['checkall']);
$fname = mysql_escape_string($_POST['firstname']);
$sql = "DELETE from `bpo`.`users` (`uid` ,`fname`)
WHERE UID IN (".$deleteid.")";
My data doesnt go to delete.php. idk why. I need help on deleting the checked rows when I push delete button and automatically reflects to my database. The change have to appear on screen without refreshing (AJAX) and with the use of implode. Thank you.
In your form change name="checkall" to name="checkall[]" to allow for multiple values.
Keep in mind that if no options are checked $_POST['checkall'] will be undefined which will generate an Undefined index notice. Use isset or array_key_exists.
If $deleteid is empty (like array()) you query will be malformed, ie.
DELETE from `bpo`.`users` (`uid` ,`fname`) WHERE UID IN ()
// unexpected ) -- ^
This will give you an SQL error. IN clause may not be empty.

How to display pg_query results in a table using PHP?

I'm trying to display the results of my query in a neatly formatted table but I'm pretty new to PHP so I'm at a bit of a loss. Currently I have this:
$dbconn = pg_connect("host=localhost port=5432 dbname=mary");
$result = pg_query($dbconn, $selectStmt);
$resultArr = pg_fetch_all($result);
print_r($resultArr);
Assume $selectStmt = SELECT State, Name FROM perez.pop WHERE Name LIKE '%Alabama%';
When I print this, I get the following:
Array ( [0] => Array ( [state] => 1 [name] => Alabama ) )
How could I place this into a table where the columns are "state" and "name" along with one more column in which I plan to place a link to a different page?
Also, can anyone clarify how the $resultArr looks when I get multiple rows as a result of my query?
EDIT: I'd like the output to look something like this:
State | Name | Follow link
___________________________________________________
32 Alabama <some link to a php page>
2 Alabama <another link>
You can just loop in your array and print your table while looping, something like
$resultArr = pg_fetch_all($result);
//print_r($resultArr);
echo '<table>
<tr>
<td>State</td>
<td>Name</td>
</tr>';
foreach($resultArr as $array)
{
echo '<tr>
<td>'. $array['State'].'</td>
<td>'. $array['Name'].'</td>
</tr>';
}
echo '</table>';
$query = pg_query("SELECT * FROM user");
$users_arr = pg_fetch_all($query);
// render thead
$thead = '<thead>
<tr>';
foreach($users_arr[0] as $key => $value) {
$thead .= '<th>' . $key . '</th>';
}
$thead .= '</tr>
</thead>';
// render tbody
$tbody = '<tbody>';
foreach($users_arr as $key => $value) {
$tbody .= '<tr>';
foreach($value as $k => $v) {
$tbody .= '<td>' . $v . '</td>';
}
$tbody .= '</tr>';
}
$tbody .= '</tbody>';
// render table
$table = '<table>' . $thead . $tbody . '</table>';
echo $table;

Google Analytics API v3 how to extract values?

I'm a newbie at GA API so I have no clue how to extract results the correct way in this case.
e.g. I'm trying to extract avgTimeOnPage values based on filtering from ga:pagePath = ...
But each one is returning a single digit value on ga:pagePath.. so I'm thinking the ga:pagePath and ga:avgTimeOnPage results are not being displayed correctly. Maybe I'm not extracting the right way.
Anyone who can help would be greatly appreciated.
$ids = 'ga:123456789';
// $start_date $end_date already defined
$filter = 'ga:pagePath==/folder/somepage.html';
$metrics = 'ga:avgTimeOnPage';
$optParams = array('dimensions' => 'ga:pagePath', 'filters' => $filter);
$data = $service->data_ga->
get($ids, $start_date, $end_date, $metrics, $optParams);
foreach($data['totalsForAllResults'] as $rows) :
echo $rows['ga:pagePath']; // why returning a single digit value?
echo $rows['ga:avgTimeOnPage']; // also returns a single digit
endforeach;
$data['totalsForAllResults'] will return a single row that is the total row. You are looking for the values not the totals. so you should use:
foreach ($data->getRows() as $row) :
And then you can iterate $rows for every cell.
Check this full example:
private printDataTable(&$results) {
if (count($results->getRows()) > 0) {
$table .= '<table>';
// Print headers.
$table .= '<tr>';
foreach ($results->getColumnHeaders() as $header) {
$table .= '<th>' . $header->name . '</th>';
}
$table .= '</tr>';
// Print table rows.
foreach ($results->getRows() as $row) {
$table .= '<tr>';
foreach ($row as $cell) {
$table .= '<td>'
. htmlspecialchars($cell, ENT_NOQUOTES)
. '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
} else {
$table .= '<p>No Results Found.</p>';
}
print $table;
}
source: https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide#working

Categories