I'm trying to load data from database and display it in table like here:
http://img196.imageshack.us/img196/1857/cijene.jpg
In database I have two tables:
cities (id, name)
prices (id, city1_id, city2_id, price)
For example, the printed table for 4 cities would look like this:
<table>
<tr>
<td>city1</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> price_city1-city2</td>
<td>city2</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> price_city1-city3</td>
<td> price_city2-city3</td>
<td>city3</td>
<td> </td>
</tr>
<tr>
<td> price_city1-city4</td>
<td> price_city2-city4</td>
<td> price_city3-city4</td>
<td>city4</td>
</tr>
</table>
Does someone know what's the PHP statement to echo this kind of tables?
// This single query gets all required data
// NOTE: this query assumes that your price data is entered
// such that from_city always alphabetically precedes to_city!
$sql =
"SELECT a.name AS from_city, b.name AS to_city, price ".
"FROM prices ".
"INNER JOIN cities AS a ON a.id=prices.city1_id ".
"INNER JOIN cities AS b ON b.id=prices.city2_id";
// connect and do query
$conn = mysql_connect($host, $user, $pass);
mysql_select_db($db, $conn);
$q = mysql_query($sql, $conn);
// Stuff all data into an array for manipulation;
// keep list of all cities mentioned
$price = array();
$cities = array();
while (($res = mysql_fetch_assoc($q)) !== false) {
$from = $res['from_city'];
$cities[ $from ] = true;
$to = $res['to_city'];
$cities[ $to ] = true;
$price[$to][$from] = $res['price'];
}
// Invert to get alphabetical list of cities
$cities = array_keys($cities);
sort($cities);
$num = count($cities);
// some utility functions
function table($rows) {
return '<table>'.join($rows).'</table>';
}
function row($cells) {
return '<tr>'.join($cells).'</tr>';
}
function cell($text) {
$text = (string) $text;
if (strlen($text)==0)
$text = ' ';
return '<td>'.$text.'</td>';
}
// The data is now in the desired order;
// produce output as HTML table
$rows = array();
for ($to = 0; $to < $num; ++$to) {
$t = $cities[$to];
$cells = array();
for ($from = 0; $from < $to; ++$from) {
$f = $cities[$from];
if isset($price[$t]) && isset($price[$t][$f])
$text = $price[$t][$f];
else
$text = '';
$cells[]= cell($text);
}
$cells[]= cell($t); // add destination-label
for ($from = $to+1; $from < $num; ++$from) // pad to proper number of cells
$cells[]= cell('');
$rows[]= row($cells);
}
$html = table($rows);
// show results!
echo $html;
I've used a very simple approach to converting the results of a query to an HTML table.
I test that $query_result is true and fetch the results as an associative array...
$query_result = mysqli_query($db, $query);
if ($query_result) {
while ($columns = mysqli_fetch_assoc($query_result)) {
echo "<tr>\n";
foreach ($columns as $name => $column) {
echo "<td>";
printf("%s",$columns[$name]);
echo "</td>\n";
}
echo "</tr>\n";
}
}
EDIT: Now I've been able to look at your table, I can see that I haven't really answered your question. The query is obviously very important. Does the question become 'how do I create a query which returns results which can be turned into a table by my simple-minded approach?'
I hope someone else has a few ideas.
This is somewhat at the edge of practicality, but I'm approaching this problem more as an exercise in "doing it right."
I would do a simple select of each table and insert in to an array:
$query1 = "SELECT * FROM cities";
$query2 = "SELECT * FROM prices";
$results1 = mysql_query( $query1 );
$results2 = mysql_query( $query2 );
while( $rows = mysql_fetch_array( $results1 ) ) $cities[] = $row['name'];
while( $rows = mysql_fetch_array( $results2 ) ) $prices[] = array(
$row['city1_id'],
$row['city2_id'],
$row['name']
);
I would then use this to dynamically create two javascript lists:
$java_array1 = "var Cities = new Array;\n";
foreach( $cities as $key=>$city ) $java_array1 .= "Cities[$key] = \"$city\";\n";
$java_array2 = "var Prices = new Array;\n";
foreach( $cities as $key=>$price ) $java_array2 .= "Prices[$key] = new Array(
\"{$price[0]}\",
\"{$price[1]}\",
\"{$price[2]}\",
);\n";
I would next output a table with carefully crafted ids for each cell. I would use code very similar to that in the first answer, but I would give each cell a unique id of "cell-<row>-<col>".
The last thing I would do would be whip up some onload javascript which would populate the table using the appropriate pairings. My javascript is quite rusty, but it would look something like this (NOTE: pseudocode follows):
n = 1;
for( var i in cities )
{
// set city names on the diagonal
document.getElementById( 'cell-'&i&'-'&i ).innerHTML = names[i];
n = n + 1;
}
for( var j in prices )
{
// use the city IDs in the prices array (see earlier code initializing
// prices array) to place the prices
document.getElementById( 'cell-'&prices[1]&'-'&prices[2] ).innerHTML = prices[0];
}
I almost certainly messed up some of that javascript; use at your own risk.
This is a lot more complex than the simpler answer given above, but this is the only way I can think of doing it so that it makes "sense." Basically, with this method, you place everything where it should be, and you don't have to worry about odd tables and weird selects.
Related
Doesn't anyone know how to rotate the result table from a join of tables ?
Better explain
This is my result
This is what i want
and finally this is my code:
<div id="encuesta">
<?php
$y = 0;
$Query1 = $Conexion->query("SELECT ID_Encuesta,Encuesta_Nombre FROM encuestas");
while($row1 = $Query1->fetch_assoc())
{
$y++;
$x = 0;
?>
<h4><?php echo $y; ?> - <?php echo $row1['Encuesta_Nombre']; ?></h4>
<table class="table table-bordered" id="table<?php echo $row1["ID_Encuesta"]; ?>">
<tbody>
<?php
$Query2 = $Conexion->query("SELECT ID_Pregunta,Pregunta_Nombre,Pregunta_Pregunta,Pregunta_Tipo FROM preguntas WHERE pregunta_encuesta = '$row1[ID_Encuesta]'");
while($row2 = $Query2->fetch_assoc())
{
echo '<tr>';
echo '<td class="bg-primary" style="color:white;">'.$row2['Pregunta_Nombre'].' </td>';
$Query3 = $Conexion->query("
SELECT
(
CASE
WHEN A.Pregunta_Tipo = '1' THEN C.Etiqueta_Numero
WHEN A.Pregunta_Tipo = '2' THEN B.Respuesta_Respuesta
WHEN A.Pregunta_Tipo = '3' THEN B.Respuesta_Respuesta
WHEN A.Pregunta_Tipo = '4' THEN C.Etiqueta_Numero
ELSE 1
END) AS Respuesta
FROM preguntas AS A
JOIN respuestas AS B
ON A.ID_Pregunta = B.Respuesta_Pregunta
LEFT JOIN etiquetas AS C
ON B.Respuesta_Respuesta = C.ID_Etiqueta
WHERE B.Respuesta_Pregunta = '$row2[ID_Pregunta]'
");
while($row3 = $Query3->fetch_assoc())
{
echo '<td>'.$row3['Respuesta'].'</td>';
}
echo '</tr>';
}
?>
</tbody>
</table>
<?php
}
?>
well, to explain my code, the first $Query1 is a consult to the encuestas table to get the thead and the relation with the $Query2,
The $Query3 its to get the value what I need to show on the tbody.
Here is my DB SQL Fidle
You have 2 options:
You can change your query
or you can change your php code.
while($row3 = $Query3->fetch_assoc())
{
echo '<td>'.$row3['Respuesta'].'</td>';
}
To change your query I need to see how the database looks like etc.
For the php code
You can push the code in an array list.
and then push the arraylist into the tables.
I suggest you change the query.
You need to create one array with your results and call this method, it will to transpose an array and then print your table again, check this sample https://3v4l.org/v9VsV
function transposeArray($array)
{
$i = 0;
$transpose = [];
while ($columns = array_column($array, $i++))
{
$transpose[] = $columns;
}
return $transpose;
}
We have a page tcount.php where we fetch counts for BOTH keyword1 and keyword2 occuring anywhere in a text field in mysql database using php script. The counts are displayed as hyperlinks. Now after that, we want that if someone clicks on the hyperlinks, they will see the detailed results in showt.php page showing those rows of the database corresponding to only those text field containing BOTH keywords.
The url of the second page showt.php is like
http://www.example.com/page.php?keyword=keyword1+keyword2
But problem is that it shows only those results which have keyword1 and keyword2 next to each other.
For example, keyword1 is car and keyword2 is cap and our text fields are as follows -
car cap
car best cap
car new
Then, we want it to show 1. and 2. as results but it is showing only no. 1 in the results page.
Please help.
Edit -
This is the code in page 1 tcount.php -
$kewyWordQ = $db->query("SELECT keywords FROM Table1 ");
<?php
while($row = $kewyWordQ->fetch(PDO::FETCH_ASSOC))
{$keyWord = $row['keywords'];
$keyWordsArr = explode(" ", $row['keywords']);
$countData = array();
$keyIndex = 0;
$tIndices = array();
$tArr = array();
$tIndices[] = "-1";
foreach($keyWordsArr as $keyword)
{
$t = $db->query("SELECT user_name FROM Table2 WHERE
t_text LIKE '%$keyWordsArr[$keyIndex]%'");
$tArr[] = $t;
while($row2 = $tweet->fetch(PDO::FETCH_ASSOC))
{
$found = TRUE;
foreach($keyWordsArr as $keyword1)
{
$ret = strpos(strtolower($row2['t_text']),
strtolower($keyword1));
if(($ret == 0) &&
strcmp(strtolower($row2['t_text'][0], strtolower($keyword1)[0])))
{
$found = FALSE;
break;
}
}
if($found == TRUE)
{
$ret = strpos($tIndices, $row2['t_id']);
if(($ret == 0) && strcmp($tIndices[0],
$row2['t_id']))
{
$tIndices[] = $row2['t_id'];
$countData[] = $row2['user_name'];
}
}
}
$keyIndex++;
}
?>
<tr><td><?php echo $row['keywords'];?></td>
<td><a href="showt.php?keyword=<?php echo
urlencode($keyWord); ?>" target="_blank"><?php echo count($countData); ?
></a></td>
<td><a href="showt.php?keyword=<?php echo
urlencode($keyWord); ?>" target="_blank"><?php echo
count(array_unique($countData)); ?></a></td>
</tr>
<?php } ?>
And this is the code in page 2 showt.php -
$keywords = $_GET['keyword'];
$sql="SELECT col1, col2, col3 from t AS s INNER JOIN users AS p ON
s.user_name=p.user_name where s.t_text LIKE '%$keywords%'
The WHERE statement of your query should look like:
WHERE my_text_field LIKE ?
and the binded parameter should be %$keyword1%$keyword2%
In order to define the $keyword1 and $keyword2 variables you can do something like:
list($keyword1, $keyword2) = explode(' ', $_GET['keyword']);
or you can simply use "%" . implode('%', explode(' ', $_GET['keyword'])) . "%" in case you have multiple possible keywords
There is a two way
one is hard way doing by php and mysql
$keyword = $_GET('keyword');
$keywordArray = explode(" ",$keyword);
$queryString = "";
foreach($keywordArray as $key=>$value) {
$queryString .= " column_name LIKE '%$value%' OR";
}
"SElECT * FROM table WHERE ".$queryString
second is mysql itself, that is Full text search
I have a MySQL table with stock information including what main industry sector and sub sector a stock belongs to (for example the Coca-Cola stock belongs to the industry sector "Consumer Goods" and to the sub sector "Beverages - Soft Drinks".
$SQL = "SELECT name, industrysector, subsector FROM Stocks WHERE economic_indicator_type = 'Stock' GROUP BY industrysector, subsector, name";
$result = mysql_query($SQL) or die ("Error in query: $SQL. " . mysql_error());
while ($row = mysql_fetch_row($result)) {
$stocks[$i]['name'] = $row[0];
$stocks[$i]['industrysector'] = $row[1];
$stocks[$i]['subsector'] = $row[2];
$i++;
}
$stocksTotals = array();
foreach($stocks as $amount) {
$stocksTotals[$amount['industrysector']] = $stocksTotals[$amount['industrysector']].", ".$amount['name'];
}
foreach($stocksTotals as $name => $amount) { echo $name.": ".substr($amount,1)."<br>"; }
My problem is that I don't get the code to handle the third level. I want to first output all of the industry sectors (Basic material for example), then all subsectors (Basic Resources for example) for each industry sector, then all names of the stocks corresponding to each subsector.
Currently I only get industry sector and then the stock name, because I fail to understand how to handle this in the array handling code.
Any advise would be highly appreciated! I have put a image here (http://imageshack.us/photo/my-images/853/mysqltophp.gif/) for better reference.
Thanks!
the foreach loop needs to be like this:
//considering you want the value as "$amount['industrysector'], $amount['name']"
foreach($stocks as $amount) {
// $stocksTotals[$amount['industrysector']] = $amount['industrysector'] .", ".$amount['name'];
echo $amount['industrysector'].": "."$amount['industrysector'], $amount['name']"."<br>";
}
you dont need another foreach loop.
Edit: you would need to change the way you fetch your rows too,
while ($row = mysql_fetch_assoc($result)) {
$stocks[$i]['name'] = $row['name'];
$stocks[$i]['industrysector'] = $row['industrysector'];
$stocks[$i]['subsector'] = $row['industrysector'];
$i++;
}
foreach($stocks as $amount) {
$output = "$amount['industrysector'] : $amount['industrysector'], $amount['subsector']";
if( $amount['name'] !== '' )
$output .= "<br>" . $amount['name'];
";
}
I'm trying to create a dynamic list (5 row results) in php by first getting data from one table then using a resulting var to get the latest uploaded "image_links" (just 1 from each of the 5 artists) from another table -- then echo out.
The code here gives me the only one row with the latest image. When I comment out the "// get the latest image link uploaded ///" section of the code I get the 5 rows of different artists I really want but, of course, w/o images. I tried (among a bunch of things) mysql_result() w/o the while statement but that didn't work.
So what am I missing?
Thanks
Allen
//// first get the artists followed ////////////////
$QUERY= "SELECT * FROM followArtist WHERE user_id = $user_id ";
$res = mysql_query($QUERY);
$num = mysql_num_rows($res);
if($num>0){
while($row = mysql_fetch_array($res)){
$artist_name = $row['artist_name'];
$artist_id = $row['artist_id'];
$date_lastSent = $row['date_lastSent'];
$date_artPosted = $row['date_artPosted'];
$date_notePosted = $row['date_notePosted'];
//// get new notice data /////
if ($date_artPosted >= $date_lastSent) {
$artp = "new artwork posted";
}else{
$artp = "";
}
if ($date_notePosted >= $date_lastSent) {
$notep = "news/announcement posted";
}else{
$notep = "";
}
if ($artp!="" && $notep!="") {
$and = " and<br />";
}else{
$and = "";
}
if ($artp=="" && $notep=="") {
$no = "No new images or news posted since your<br /> last visit, but we'll let you know when there is.";
}else{
$no = "";
}
//////// get the latest image link uploaded ////////////////////////////////////
$QUERY2="SELECT image_link FROM artWork WHERE artist_id ='$artist_id' AND make_avail = '1' ";
//ORDER BY date_submit DESC
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 ){
while($row = mysql_fetch_assoc($res)){
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
//////// end of get the latest images uploaded ////////////////////////////////
echo "<tr align=\"center\" height=\"115px\">
<td align=\"left\" width=\"15%\"> <a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\">
<img src=slir/w115-h115/$path$image_link /></a></td>
<td align=\"center\" width=\"80%\"
<span class=\"deviceMedLtGrayFont\">$artist_name</span>
<br /><br />
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$artp</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$and$no</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$notep</a>
</td>
</tr>";
} //// end bracket for getting latest image link
} ///loop end for getting followed artist data
} ///end: if ($num>0) clause<code>
If I read your code correctly, I see you looping using data from query1 in the control structure, and a lookup on query2 within each loop. You are reusing the variables in your loop1 control structure for query2 ($num and the query handle ($res)) for the second loop. Probably not desirable within the loop.
You're sharing the variables $num and $res between the two queries ... your original properties will be overwritten when the second query is run. Use different property names for the inner query.
Example of problem:
$result = QueryA();
while( $row = $result->getRow() )
{
// -- You're overwriting the original result here ...
$result = QueryB();
// Next time the loop runs, it will run using the result from QueryB();
}
So change ...
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 )
{
while($row = mysql_fetch_assoc($res))
{
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
to
$res2 = mysql_query($QUERY2);
$num2 = mysql_num_rows($res2);
if($num2 > 0)
{
while($row2 = mysql_fetch_assoc($res2))
{
$image_link= $row2['image_link'];
}
this is a mess - as others have said you're using the same variables for different purposes.
That you're storing integers which seem to represent enumerations in a char field is bad.
You're iterating through the second result set to find the last record (from an unsorted result set!).
You only need one query - not 2.
SELECT f.artist_name, f.artist_id, f.dateLastSent....
SUBSTR(
MAX(
CONCAT(DATE_FORMAT(date_submit, '%Y%m%d%H%i%s'), a.image_link)
), 15) as img_link
FROM followArtist f
LEFT JOIN artWork a
ON (a.artist_id=f.artist_id AND a.make_avail = '1')
WHERE user_id = $user_id
GROUP BY f.artist_name, f.artist_id, f.dateLastSent....
Can anyone help me on how to do this
All the data should come from database and arrange like what has show above.Thanks..
How is this data stored, exactly?
You would ultimately order by the business name and every time a new first character came up, print that as a title.
$get_businesses = mysql_query("SELECT * FROM businesses ORDER BY name ASC");
$last_character = '';
while($res_businesses = mysql_fetch_assoc($get_businesses))
{
$business_name = $res_businesses['name'];
$first_character = strtolower( sub_str($business_name, 0, 1) );
if($first_character !== $last_character){
print '<h1>'.strtoupper($first_character).'</h1>';
}
print '<p>'.$business_name.'</p>';
$last_character = $first_character;
}
If it's from your array
$last_character = '';
foreach($businesses as $business)
{
$business_name = $business['name'];
$first_character = strtolower( sub_str($business_name, 0, 1) );
if($first_character !== $last_character){
print '<h1>'.strtoupper($first_character).'</h1>';
}
print '<p>'.$business_name.'</p>';
$last_character = $first_character;
}
It's ultimately untested but hopefully it'll give you what you need :)
This is a concept not the full code !
//connect to database
$sql="SELECT * FROM ORDER BY DESC";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
//write a dynamic table here
echo "< table > < td >";
if($row['name'] == 'Letter name') //the first letter then go to a new column < br >
}
echo "< /table >";