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);
?>
Related
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.
Is it possible to save SQL result in variable and then use that to echo data anywhere on my site.
for example
$result=mysqli_query("SELECT * FROM table");
and then use that variable to show that data anywhere else on site and even repeat it in some loop
$show=mysqli_fetch_assoc($result)
I tried that in for while loop and it echo my result only once.
my full code
$result=mysqli_query("SELECT * FROM table");
$r=mysqli_query("SELECT * FROM table2");
while($x=mysqli_fetch_assoc($r))
{
echo $x["ID"];
while( $show=mysqli_fetch_assoc($result))
{echo $show["ID"];}
}
Make a $table1_array and a $table2_array and instead of echo $x use $table1_array[] = $x. Since the table2 - select needs nothing from table1 you should read it only once. Make no inner loop, make two separate loops.
EDIT:
to clarify:
$result=mysqli_query("SELECT * FROM table");
$table_array = array();
while( $show=mysqli_fetch_assoc($result)){
$table_array[] = $show;
}
$r=mysqli_query("SELECT * FROM table2");
while($x=mysqli_fetch_assoc($r))
{
echo $x["ID"];
foreach($table_array as $show){
echo $show["ID"];
}
}
I want use mysql_data_seek with PDO from google search I found that it should looks like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
however it's not work, what I do wrong?
this is my code:
$query = "SELECT name,age FROM users";
$q = $db->prepare($query);
$q->execute();
$q->setFetchMode(PDO::FETCH_ASSOC);
$arrayData = $q->fetchAll();
foreach ($arrayData as $row){
echo $row['name'] ." ";
echo $row['age'] ."<br>";
}
$result = $q->fetch(PDO::FETCH_OBJ,PDO::FETCH_ORI_ABS,4);
var_dump($result);
I just want get the 5th row in object form from the last run query. I don't want run this query again (as some guys told me) I just want the results from sql buffer.
the var_dump result is: bool(false)
any ideas?
EDIT:
thanks for your answers and sorry but maybe I don't explain myself as well. I like the trick with JSON but the point is that the 5th row is example. I just want use the result of the query from the buffer with PDO exactly as I did it with mysql_data_seek in regular mysql (change the cursor). is it possible? I like all the tricks but that not what I look for.
the PDO 'cursor' default is PDO::CURSOR_FWDONLY that means that cursor can't back to zero like it happens with mysql_data_seek to allow cursor back to zero it necessary define use 'scrollable cursor'
example:
$db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
before use it like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
$result = $arrayData[4];
is all you need.
If you want the 5th row result you can do like this:
$result = json_decode(json_encode($arrayData[4]), FALSE);
var_dump($result);
or something like this:
$object = new stdClass();
foreach ($array as $key => $value)
{
$object->$key = $value;
}
Just curious! why do you need the object form?
EDIT (this will give the object form of the 5th row):
$index = 0;
$fifthRow = new stdClass();
while($row = $q->fetch())
{
if($index++==4)
$fifthRow = json_decode(json_encode($row), FALSE);
}
You could do it like this:
$c = 1;
$saved=null;
while($row = $q->fetch()){
if($c==4){
$saved = clone $row;
};
$c++;
somethingelse;
}
$saved will then contain the 4th element as an object with almost no extra overhead calculations.
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
I have this script
$query = "SELECT id,last_name,first_name FROM users WHERE tmima_id='6'";
$result = #mysql_query($query);
while($row = mysql_fetch_array($result))
{
$i = 3;
$emp_id = $row['id'];
$cell = 'A'.$i;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($cell, $row['last_name']. $row['first_name']);
$i++;
}
But in the .xls file it prints only one user. Why id doesnt print all of the users ? W
Thanks in advance.
I make the change you said with $sheet
$query = "SELECT id,last_name,first_name FROM users WHERE tmima_id='6'";
$result = #mysql_query($query);
while($row = mysql_fetch_array($result))
{
$i = 3;
$emp_id = $row['id'];
$cell = 'A'.$i;
$sheet->setCellValue($cell, $row['last_name']. $row['first_name']);
$i++;
}
But it still prints out only one record. And yes when i run the query in phpmyadmin it returns more than one record.
How can i print out data from mySql table.. What is going wrong ?
I am pretty sure it is because you are using a unique identifier (WHERE tmima_id='6'). It is only finding the results for that one unique identifier and displaying that. Hope this helps.
$i is being reset to row 3 every loop. Set $i=3; before the while loop, not inside it.