PHP/ARRAY/HTML TABLE -- How come this repeats the same thing across the whole <td>? - html

Im trying to turn an array of friends names: $friends['name'] from the Facebook Graph API into a table with 4 columns across with one persons name in each box.
The problem:
I have it making a table and putting peoples names in the cells of the table, however, it repeats each persons name across all 4 in a row instead of putting a unique name in each box. However the next row starts with a new name.
I would greatly appreaciate anybody who can help point out where Ive gone wrong and help me correct it:
<?
$friends_url = "https://graph.facebook.com/".$user_id."/friends?access_token=".$access_token;
$friends_json = file_get_contents($friends_url);
$friends_data = json_decode($friends_json, true);
$friends_total = count($friends_data['data']);
$cols = 4;
for ($i = 0; $i < $friends_total; $i++)
{
$friends = $friends_data['data'][$i];
echo "<tr>";
for ($c=0; $c<$cols; $c++)
{
$n = $i+$c;
if ( $n < $friends_total)
{
echo "<td>".$friends['name']."</td>";
}
else
{
echo "<td></td>";
}
}
echo "</tr>";
$i += ($c-1);
}
?>

Because you're looping 4 times for each friend and your loop counter for 'columns' is inside that loop, try something more like this:
$cols = 4;
$current_col = 0;
echo "<tr>";
foreach ($friends_data['data'] as $friend)
{
echo "<td>".$friend['name']."</td>";
if (($current_col++)%$cols == 0){
echo "</tr><tr>";
}
}
while (($current_col++)%$col !=0){
echo "<td> </td>";
}
echo "</tr>";
This loops through all the friends, keeping a counter of how many have been printed. After 4 (/or whatever $cols is set to) it spits out a new row
When the friends are all printed out, it starts a new loop to fill in the end of the last row with empty cells, then ends the row

Related

Way to make row count be 0 if no date match and second,third,etc while loop row counts

<?php
if($result = $db->query("SELECT * FROM table")) {
if($count = $result->num_rows) {
echo '<p class="lead">Number of callbacks for today is: ', $count, '</p>';
while($row = $result->fetch_assoc()) {
if ( $row['field'] == date("Y-m-d") ) {
echo $row['otherfield'], '<br>';
}else{
echo "Nothing", '' , '<br>';
}
}
}
}
?>
I have a simple field date verses server date test used in conjunction with a while loop to bring up any callbacks each day if they are due. My issue is that the row will show a nothing for every row so I'll have twenty(example) rows of the text 'nothing' display. I know I could simply place everything in a function and then use the if/else statement outside of the function to display callbacks or not display callbacks....but is there a way to reset the loop counter to zero if the first if/else test fails? I tried placing the $count = 0; in the second else clause but this did not work.

Bootstrap grid and layout output

Suppose that I have a block of HTML:
<figure>
<img/>
</figure>
and I need to wrap them in Twitter Bootstrap 3 columns, like <div class="col-md-3">{content}</div>. I need to make rows every 4 times in the loop (to sum the 12 columns fitting the row) to make the grid.
How is the best way to achieve this?
Does Twig offer that solution easily? I would like to just pass what the each column classes I need and the "function" work out to split the columns automagically.
I'm using https://stackoverflow.com/a/16428403/1110456 as a solution, but seems that has a better way to do that. I currently use CakePHP and a framework and PHP language.
You need to try something like this. It will:
Get a count of how many objects you have in your view
Set the object counter and column counter to zero
If this is your first column, start a <div class="row">
Display the content
Increment the column counter by one
If this is column 4, or if this is your final item, close the row div
and reset the column counter.
$count = count($models);
$i = 0;
$column = 0;
foreach ($models as $model) {
if ($column == 0) {
echo "<div class='row'>";
}
echo "<div class='col-md-3'>" . "Content" . "</div>";
$column = $column + 1;
if((++$i === $count && $column !== 4) || ($column == 4)) {
echo "</div>";
$column = 0;
}
}

How to echo specific mysql data in specific places using php?

If the 'SELECT' statement is used to select data from a database then how do we echo specific rows to specific places on a page using php?
To explain this better - I am trying to SELECT * ALL FROM a table but to echo multiple rows to particular places on the html page using php.
So, imagine that my entire mark up and css has 20 thumbnails on a page and each thumbnail has data and an image that is unique to each thumbnail....do I have to replicate the below 20 times?
I am thinking that the best way to do this (which is probably completely wrong) is to use this statement
SELECT * FROM name_of_table WHERE ID = 4 >>> i.e. where I'd like that specific data echoed....
So, if I have 20 thumbnails do I do this 20 times?
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT * FROM name_of_table WHERE ID = 4;")
or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Name:</th> <td>".$info['name'] . "</td> ";
Print "<th>Product:</th> <td>".$info['product_name'] . " </td></tr>";
}
Print "</table>";
?>
And, rinse and repeat but I change the below statement each time for each thumbnail (each thumbnail has unique data that comes from each row on the MySQL)
SELECT * FROM name_of_table WHERE ID = 4;
What is the best way of doing this?
Thanks!
Simple example.. First get the data with wanted ID:s. Create function for data request.
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT * FROM name_of_table WHERE ID IN (2,3,4,5,6);")
or die(mysql_error());
// This holds all data rows
$data_array = array();
while($info = mysql_fetch_array( $data ))
$data_array[] = $data;
// Function for rendering data to html
function getItemHtml($id) {
$html = "";
foreach($data_array as $row) {
if ($row['ID'] == $id) {
$html = "<td>" . $row['title'] . "</td>";
// etc.. create item html here
break;
}
}
return $html;
}
// To create one item just call this with item id.
echo getItemHtml(4);
?>

How can I choose only 2 columns without changing the SELECT query?

I am generating a table with this code:
if ($arch = $pdo->prepare("SELECT one, two, three, four FROM numbers)) {
$arch ->execute();
$data = $arch->fetchAll();
echo '<table>';
foreach ($data as $row){
echo '<tr>';
foreach ($row as $col){
$col=nl2br($col);
echo '<td>'.$col.'</td>';
}
echo '</tr>';
}
echo '</table>';
}
}
This populates a table with 4 columns.
How can I choose only 2 columns without changing the SELECT query?
In other words, how can I choose the columns I want to populate the table? for example I would like to use only "three" and "four"...
I read about fetchAll(PDO::FETCH_COLUMN, 0) but this seems to pick only one column. The same goes for fetchColumn(). I want to pick more than one so I can populate my table with only the columns I need.
Just add a selector on the second foreach, to filter the columns you want:
....
foreach($row AS $col => $value){
if($col == 'your_column_name'){
echo '<td>'.nl2br($value).'</td>';
}
}
....
Make sure you have your 'fetchmode' on associative, which makes sure the pdo-result object contains a associative array with key-indexes.
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
Alternatively, you can specify the columns you want as an array beforehand, and iterate over that array rather than the columns in the row.
$columns = array('I_like_this_column', 'this_one_too');
foreach ($columns as $colName)
echo '<td>' . nl2br($row[$colName]) . '</td>';
This has the added advantage of letting you specify the order the columns will appear in your output without changing your query.
And, as with #stUrb's answer, you need to turn on PDO::FETCH_ASSOC for this to work.

nested while loop mysql_fetch_array

I have a set of nested while loops to compare to mysql queries to each other. Here is the code:
while($row = mysql_fetch_array($resultbat))
{
$drafted = 0;
while($crossedRow = mysql_fetch_array($crossedAnswer))
{
if($row['NAME'] == $crossedRow['name'])
{
$drafted = 1;
}
else
{
$drafted = 0;
}
}
if ($drafted == 1)
{
echo "<tr class='drafted' id='" . $row['NAME'] . "'>";
}
else if($n&1)
{
echo "<tr id='" . $row['NAME'] . "'>";
}else
{
echo "<tr class='alt' id='" . $row['NAME'] . "'>";
}
...}
In the $resultbat is a list of all players, and in the $crossedAnswer is a list of a few players that should be marked. For each player I want to see if they are in the $crossedAnswer list of players. If they are I want to mark the class of that html element to drafted.
Thanks in advance.
I think you'll either need to:
open the cursor on $crossedAnswer for each row from $resultbat (open it at the beginning of each loop through, and close it at the end, which effectively runs that query for each for in resultbat), or
fetch all of the rows from the $crossedAnswer resultset into a structure, and look through that structure for each row from $resultbat, (to avoid running the same query multiple times against the database), or
ensure that both $resultbat and $crossedAnswer are ordered by key value, and do just a single loop; open both cursors, fetch a row from each, and then compare the key values to determine which resultset is "behind", and which one to fetch from (this is more efficient, but is more complicated code to write and test), or
if these resultsets are from the same MySQL server, rewrite this as a single query, and let MySQL do the work of joining the rows together, and process just a single resultset.
Personally, I would opt for the last. I would let MySQL do the join, get a single resultset back, and a single loop.
The query to get the resultset would be of the form:
SELECT b.*
, IF(a.name IS NOT NULL,1,0) AS drafted
FROM (
query_for_$resultbat
) b
LEFT
JOIN (
query_for_$crossedAnswer
) a
ON b.name = a.name
Note that if a matching row is found in a, then the drafted column will return a 1, otherwise, it will return a 0.
The code to handle this resultset, based on the original code could be something like this:
while($row = mysql_fetch_array($result))
{
$class = "";
if($row['drafted'] == 1
{
$class = "class='drafted' ";
}
else if($n&1)
{
$class = "";
}
else
{
$class = "class='alt' ";
}
echo "<tr " . $class . " id='" . $row['NAME'] . "'>";
...
}