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

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.

Related

MYSQL How can I make dropdown list?

I created a new table in workbench where I want to put a season of a soccer championship.
I don't want to write down every time the team's names, can you help me pls, how can I make like a dropdown list (or set of values, what are the only options for that column), when I begin to type "Bay..." its automatically offer "Bayern München" as the only option.
I don't know how much will this help, but I have made a dropdown list for something else and I hope my way might give you an idea:
foreach ($dbo->query($sql) as $row) //Array or records stored in $row
{
if($row[id]==10)
{
echo "<option value=$row[id] selected>$row[name]</option>";
}
else
{
echo "<option value=$row[id]>$row[name]</option>";
}
}
echo "</select>"; // Closing of list box
As the same answer above, but using short-hand ternary operator instead of if-else statement, and don't forget to use ' or " when reference to object string index.
foreach ($dbo->query($sql) as $row) //Array or records stored in $row
{
printf("<option value='%s' %s>%s</option>", $row['id'], $row['id'] == 10 ? 'selected' : '', $row['name']);
}
}
echo "</select>"; // Closing of list box

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);
?>

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

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