when select data from database using php-mysql and display in html table it shows as (A).
but i want to display it as (b)
help me...
Sample (and very simple) code would be:
// assuming the PDO connection is established and kept in $db
$st = $db->prepare("SELECT Date, Num, Value1, Value2 FROM the_table");
if ($st->execute()) {
$previousDate = NULL;
$previousNum = NULL;
while ($row = $st->fetch()) {
echo '<tr>';
echo '<td>';
if ($previousDate != $row['Date']) {
echo $row['Date'];
$previousDate = $row['Date'];
}
echo '</td>';
echo '<td>';
if ($previousNum != $row['Num']) {
echo $row['Num'];
$previousNum = $row['Num'];
}
echo '</td>';
echo '<td>'. $row['Value1'] .'</td>';
echo '<td>'. $row['Value2'] .'</td>';
echo '</tr>';
}
}
Related
I'm a beginner in php and my instructor gave us a task. How can I get the value of the column in the selected row?
<?php
include 'connection.php';
$sqlsearch = "SELECT `Student_ID`,`First_Name`,`Last_Name`,`Year_Level`,`Enrollment_Date`,`Status` FROM `student_info`";
$sqlresult = $connection->query($sqlsearch);
$searchInput = "";
if($sqlresult->num_rows <= 0){
echo "No found Result";
}
if(!empty($_GET["search"])){
$searchInput = trim_input($_GET["search"]);
$sqlsearch = "SELECT `Student_ID`,`First_Name`,`Last_Name`,`Year_Level`,`Enrollment_Date`,`Status` FROM `student_info`
WHERE `Student_ID` = '". $searchInput ."' OR `First_Name` LIKE '%". $searchInput ."%' OR `Last_Name` LIKE '%". $searchInput."%'";
$sqlresult = $connection->query($sqlsearch);
if($sqlresult->num_rows > 0){
while($row = $sqlresult->fetch_assoc()){
generateResult($row);
}
}else{
}
}
else{
while($row = $sqlresult->fetch_assoc()){
generateResult($row);
}
}
function generateResult($row){
echo "<tr>";
echo '<td style="color:#33F0FF"> '. $row["Student_ID"] .'</td>'; //Plz get the student ID of the selected ID.
echo '<td>'. $row["First_Name"] .' '. $row["Last_Name"] .'</td>';
echo '<td>'. $row["Year_Level"].'</td>';
echo '<td>'. $row["Enrollment_Date"].'</td>';
if($row["Status"] == "Active"){
echo '<td style="color:green">'. $row["Status"].'</td>';
}else if($row["Status"] == "Dropped"){
echo '<td style="color:orange">'. $row["Status"].'</td>';
}else{
echo '<td style="color:red">'. $row["Status"].'</td>';
}
echo "</tr>";
}
?>
In the function generateResult($row)
how can I get the value of Student_ID when I click the link?
If you need student_id with anchor tag , probably you want to go to other page on clicking the link . In that case , replace :
echo '<td style="color:#33F0FF"> '. $row["Student_ID"] .'</td>';
to
echo '<td style="color:#33F0FF"> '. $row["Student_ID"] .'</td>';
Then on the xyz.php page , you will get student_id using $_GET["student_id"]
I am trying to create very simple time tracking app with only 3 values in database: description, time-spent and date and I need to group results by Date and generate HTML tables.
For example:
Today(10.07) for this date I have 3 records in database, I need to generate HTML table for this date.
Tommorow(11.07) when I create new record with new date - it creates new HTML table.
At the and I have a lot of HTML tables with specific day dates.
(HTML table for its own date).
So how to group by date and how to generate HTML tables?
The screenshot below reflects what I'm trying to achieve:
Below is my code:
function getLogs( $con ) {
$stmt = $con->prepare( "SELECT * FROM timelogsapp GROUP BY DATE ORDER BY date DESC" );
$stmt->execute();
$result = $stmt->fetchAll();
foreach( $result as $row ) {
echo '<table class="list-table">';
echo '<thead>';
echo '<span class="date">';
echo datetime();
echo '</span>';
echo '<tr>';
echo '<th>Description</th>';
echo '<th>Time</th>';
echo '<th>Date</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
echo '<tr>';
echo '<td>' . $row['description'] . '</td>';
echo '<td>' . $row['time'] . '</td>';
echo '<td>' . $row['date'] . '</td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
}
}
You can create a SQL WHERE the dates are within the wanted range. So you said you wanted to be for today, it would look like this:
UPDATE
This should create multiple queries and you can Add more to the WHERE clause, to get the custom date, I hope this gives you an idea of what you can do with.
Every record will create it's unique table, as they are inside of the foreach clause.
<?php
$today = date('d.m');
$today_query = "SELECT * FROM timelogsapp WHERE date = $today DESC";
$yesterday = date('d.m', time() - 60 * 60 * 24);
$yesterday_query = "SELECT * FROM timelogsapp WHERE date = $yesterday DESC";
$custom = "";
if (isset($_POST['date']))
{
$custom = $_POST['date'];
}
$custom_query = "SELECT * FROM timelogsapp WHERE date = $custom DESC";
$tom = new DateTime('tomorrow');
$tomorrow = $tom->format('d.m');
$tomorrow_query = "SELECT * FROM timelogsapp WHERE date = $tomorrow DESC";
function getLogs($con){
$stmt = $con->prepare("SELECT * FROM timelogsapp WHERE date = $today AND date = $yesterday AND date = $custom DESC");
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
echo '<table class="list-table">';
echo '<thead>';
echo '<span class="date">';
echo datetime();
echo '</span>';
echo '<tr>';
echo '<th>Description</th>';
echo '<th>Time</th>';
echo '<th>Date</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
echo '<tr>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.$row['time'].'</td>';
echo '<td>'.$row['date'].'</td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
}
}
?>
Of course you can make that much more dynamic by playing with some PHP. But that will select all records from timelogsapp just where the dates equal to 10.07. Then display it in descending order.
I managed to achieve the result i've been looking for.
// getting all dates from database with limit
$all_dates_query = "SELECT * FROM timelogsapp GROUP BY date(date) ORDER BY date DESC LIMIT $limit OFFSET $offset";
$stmt = $con->prepare($all_dates_query);
$stmt->execute();
$all_dates = $stmt->fetchAll();
function getLogs($con, $all_dates)
{
foreach ($all_dates as $row) {
$this_date = $row['date'];
$all_dates = "SELECT * FROM timelogsapp WHERE date(date) = date('$this_date') ORDER BY date DESC"; //getting all logs for current date
$stmt = $con->prepare($all_dates);
$stmt->execute();
$result = $stmt->fetchAll();
//generating html table with logs
echo '<table class="list-table">';
echo '<thead>';
echo '<span class="date">';
echo datetime($this_date);
echo '</span>';
echo '<tr>';
echo '<th>Description</th>';
echo '<th>Time</th>';
echo '<th>Date</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
foreach ($result as $row) {
echo '<tr>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.$row['time'].'</td>';
echo '<td>'.date('d.m.Y H:i', strtotime($row['date'])).'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
}
}
I want every different record of database to be display on each table rows, but I'm unable to retrieve different record for each row and column. Please give me suggestion where I can paste than while block so it will give different result for each row and column.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$rec_limit = 10;
$scriptname=$_SERVER['PHP_SELF'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('online_shopping'); // include your code to connect to DB.
$tbl_name="mobile_db"; //your table name
$start = 0;
$limit = 5;
$sql = "SELECT id,company,model,price,availability,image FROM $tbl_name LIMIT $start, $limit";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$company=$row['company'];
$model=$row['model'];
$available=$row['availability'];
$price=$row['price'];
}
echo "<table border='2'>";
$j = 0;
for($j = 0; $j<5; $j++)
{
echo "<tr>";
for($i = 0; $i<3; $i++)
{
echo "<td>";
echo "<table border='2'>";
echo "<tr>";
echo "<td><img src='abc.jpg' height='250' width='250'/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
echo "<table border='2'>";
echo "<tr>";
echo "<td><b>Brand : </b></td>";
echo '<td>'.$company.'</td>';
echo "</tr>";
echo "<tr>";
echo "<td><b>Model : </b></td>";
echo '<td>'.$model.'</td>';
echo "</tr>";
echo "<tr>";
echo "<td><b>Availability : </b></td>";
echo '<td>'.$available.'</td>';
echo "</tr>";
echo "<tr>";
echo "<td><b>Price : </b></td>";
echo '<td>'.$price.'</td>';
echo "</tr>";
echo "</table>";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
You need to move the table rows inside the fetch loop or store the row in an array. I have simplified your tables to make the example clearer:
$result = mysql_query($sql);
if (!$result) {
/* Error */
}
echo '<table>';
while ($row = mysql_fetch_array($result)) {
echo '<tr><td><img src="', htmlspecialchars ($row['image']), '">';
echo '<tr><td><table>';
echo ' <tr><th>Brand<td>', htmlspecialchars ($row['company']);
echo ' <tr><th>Model<td>', htmlspecialchars ($row['model']);
echo ' <tr><th>Availability<td>', htmlspecialchars ($row['availability']);
echo ' <tr><th>Price<td>', htmlspecialchars ($row['price']);
echo ' </table>';
}
echo "</table>\n";
Some notes about the code:
Test the return value of mysql_query(). The query might fail.
Escape your output using htmlspecialchars().
You should use <th> elements for your headings and style those, instead of using inline <b> elements.
I added output of $row['image'] which might not do what you want.
And do not use the deprecated mysql extension. Use PDO or mysqli instead.
In your while loop you always rewrite the same variables, after loop you have only last record saved.
In the loop, you have to save records into array.
In your code you have nested tables, but in the first one, there is only one row and one table cell which contains another table. I use just nested table.
<?php
...
$result = mysql_query($sql);
$data = array();
while($row = mysql_fetch_array($result)) {
$data[] = $row;
}
if (count($data) > 0) {
echo '<table>';
foreach ($data as $row) {
echo '<tr>';
echo '<td>Brand: ' . $row['company'];
echo '<td>Model: ' . $row['model'];
echo '<td>Availability: ' . $row['availability'];
echo '<td>Price: ' . $row['price'];
}
echo '</table>';
} else {
echo 'no records';
}
?>
Not sure I fully understand what you are trying to accomplish but try this.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$rec_limit = 10;
$scriptname=$_SERVER['PHP_SELF'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('online_shopping'); // include your code to connect to DB.
$tbl_name="mobile_db"; //your table name
$start = 0;
$limit = 5;
$sql = "SELECT id,company,model,price,availability,image FROM $tbl_name LIMIT $start, $limit";
$result = mysql_query($sql);
echo "<table border='2'>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row['company']."</td>";
echo "<td>".$row['model']."</td>";
echo "<td>".$row['availability']."</td>";
echo "<td>".$row['price']."</td>";
echo "</tr>";
}
echo "</table>";
?>
I have a a php website with some code on it to pull from a database after the user has defined some search terms and then show them a table with all their information in it
The problem is even when i do a select * from the tables, i am only getting the first row back.
Code:
$result = mysql_query("SELECT trees.*
FROM trees
INNER JOIN price
ON trees.ID=price.treeid
");
$num_rows = mysql_num_rows($result);
if($num_rows == 0) {
echo "No rows retrieved";
} else {
echo $num_rows;
}
i have 2 rows in my database:
Spruce El Sorbeous Sprucious Green Green Green 100 200
its a tree ma! true NULL NULL NULL
Mayday el daymay red green white 10 4000000
GOING DOWN true Grey true false
when i print out the $num_rows up there, it is only one.
When i print out my table below, there is only one row:
echo '<table border = 0 cellpadding=0 >';
echo '<tr>';
echo '<td><b><u>Name</b></u></td>
<td><b><u>Latin Name</b></u></td>
<td><b><u>Primary Color</b></u></td>
<td><b><u>Secondary Color</b></u></td>
<td><b><u>Fall Color</b></u></td>
<td><b><u>Trunk Color</b></u></td>';
echo '<td><b><u>Description</b></u></td>
<td><b><u>Height</b></u></td>
<td><b><u>Spread</b></u></td>
<td><b><u>Drought Resistant?</b></u></td>
<td><b><u>Flowering?</b></u></td>
<td><b><u>Fruit Producing?</b></u></td>';
echo '</tr>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>';
echo $row['name'];
echo '</td>';
echo '<td>';
echo $row['latinname'];
echo '</td>';
echo '<td>';
echo $row['primarycolor'];
echo '</td>';
echo '<td>';
echo $row['secondarycolor'];
echo '</td>';
echo '<td>';
echo $row['fallcolor'];
echo '</td>';
echo '<td>';
echo $row['trunkcolor'];
echo '</td>';
echo '<td>';
echo $row['description'];
echo '</td>';
echo '<td>';
echo $row['height'];
echo '</td>';
echo '<td>';
echo $row['spread'];
echo '</td>';
echo '<td>';
echo $row['droughtresistant'];
echo '</td>';
echo '<td>';
echo $row['flowering'];
echo '</td>';
echo '<td>';
echo $row['fruitproducing'];
echo '</td>';
echo '</tr>';
}
echo '<table>';
INNER JOIN will only return values that have NOT NULL values in both tables. You are probably joining stuff with a NULL value. Use a LEFT or a RIGHT join instead!
Since there's no example of the data in the PRICE table, I'm guessing that only one row was joined.
The question remains, why are you doing that JOIN? You're not collecting any data from the PRICE table, so what's the point.
BTW, where in the data is the ID?
Here I want to fetch the field names from the table name which is stored in the variable $table. And want to make a table headers of the field names. What's wrong with this approach I tried:
<?php
$sql=mysql_query("show fields from $table");
if(mysql_num_rows($sql))
while($res = mysql_fetch_object($sql))
{
?>
<th><?php echo $res->field; ?></th>
<?
}
else
{
echo "No data to display";
}
?>
$printTHs = true;
while($res = mysql_fetch_assoc($sql))
{
if ($printTHs)
{
printTableHeader($res);
$printTHs= false;
}
echo "<tr>";
foreach($res as $val)
{
echo "<td>" . $val . "</td>";
}
echo "</tr>";
}
function printTableHeader($res)
{
echo "<tr>";
foreach($res as $col => $val)
{
echo "<th>" . $col . "</th>";
}
echo "</tr>";
}
The query has to be
$sql=mysql_query("show columns from $table");
Use mysql_fetch_assoc() and then get the keys using array_keys(). This will return an array with all the keys.
Use foreach() to get your table headers
Not the optimal solution, but would do it:
$results = mysql_query('SELECT * FROM ' . $table);
if (mysql_num_rows($results))
{
echo '<table>';
$first = TRUE;
while ($row = mysql_fetch_assoc($results))
{
if ($first = TRUE)
{
echo '<tr>';
foreach ($row as $k => $v)
echo '<th>' . $k . '</th>';
echo '</tr>';
$first = FALSE;
}
echo '<tr>';
foreach ($row as $column)
echo '<td>' . $column . '</td>';
echo '</tr>';
}
echo '</table>';
}