Defining HTML tables within PHP - php

I'm trying to get an HTML Table output in to a specific format via PHP after it grabs information from a MySQL Database.
In HTML, I can do this:
<table cellpadding="0" cellspacing="0" class="list">
<tr>
<td style="cursor:hand" onclick="window.location.href = 'page.php?presenter=Name1'">Name1</td>
<td style="cursor:hand" onclick="window.location.href = 'page.php?presenter=Name2'">Name2</td>
<td style="cursor:hand" onclick="window.location.href = 'page.php?presenter=Name3'">Name3</td>
</tr>
<tr>
<td style="cursor:hand" onclick="window.location.href = 'page.php?presenter=Name4'">Name4</td>
<td style="cursor:hand" onclick="window.location.href = 'page.php?presenter=Name5'">Name5</td>
<td style="cursor:hand" onclick="window.location.href = 'page.php?presenter=Name6'">Name6</td>
</table>
This works great and looks nice, I have it DIV'd up and formatting nicely.
However, I need to do this by pulling down the names from MySQL and then creating a new cell when needed, then after 3 cells, create a new row.
So far, I have this:
<?php
//PRESENTERS HERE
/* connect to the db */
$connection = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($db, $connection);
/* show tables */
$result = mysql_query('SHOW TABLES', $connection) or die('cannot show tables');
echo '<h1>Presenters:</h1>';
while ($tableName = mysql_fetch_row($result))
{
$table = 'presenters';
/* Get the presenters*/
$result2 = mysql_query('SELECT presenter FROM ' . $table) or die('cannot show data from ' . $table);
}
if (mysql_num_rows($result2))
{
echo '<table cellpadding="0" cellspacing="0" class="list">';
while ($row1 = mysql_fetch_row($result2))
{
echo '<tr>';
foreach ($row1 as $key => $value)
{
echo '<td style="cursor:hand" onclick=\"window.location.href = \'page.php?presenter=' . $value . '">', $value, '</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
?>
But I'm unable to figure out how to get it to behave like the HTML one above. I also can't get the on click events to work.
The PHP form ends up with all entries on a row each, instead of three to a row.

Ahhh I see your problem for the entries in 3 rows and not one.
while($row1 = mysql_fetch_row($result2)) {
echo '<tr>';
foreach($row1 as $key=>$value) {
echo '<td style="cursor:hand" onclick=\"window.location.href = \'page.php?presenter='.$value.'">',$value,'</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
Because each time you retrieve something from the database (your while loop statement) you are opening and closing rows in the table.
You need to have a counter started outside the while loop which counts how many rows you have and when you get to the number of columns you want, reset the counter and close off the table tags.
Something like this:
$columncount = 0;
while($row1 = mysql_fetch_row($result2)){
if($columncount == 0){
echo "<tr>";
}
foreach($row1 as $key=>$value) {
echo '<td style="cursor:hand" onclick=\"window.location.href = \'page.php?presenter='.$value.'">',$value,'</td>';
}
$coloumncount ++;
//assuming you want 3 columns in your table
if($columncount == 3) {
echo "</tr>";
$coloumncount = 0;
}
}
Won't solve your onclick events but it will format the table.
Good luck!

Is the first quote for the onclick attribute accidentally getting escaped on this line?
echo '<td style="cursor:hand" onclick=\"window.location.href = \'page.php?presenter='.$value.'">',$value,'</td>';
You're also using different CSS classes between your example static HTML, and the generated HTML in your PHP sample (class="list" vs. class="db-table").

Related

Total of column in displayed result in PHP

I have a table 'tblexam' which contains State,city,candidate.I want to fetch the data from this table using where clause.I am able to fetch the data but i want to add the sum of Candidate at the last row(As Shown In Picture) how can i do that .
$sql="SELECT *
FROM tblexam
WHERE state='UP'";
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result) {
$cnt=$cnt+1; ?>
<tr class="odd gradeX">
<td class="center"><?php echo htmlentities($cnt);?></td>
<td class="left"align="left"><?php echo htmlentities($result->state);?></td>
<td class="center" align="left"><?php echo htmlentities($result->city);?></td>
<td class="center"align="left"><?php echo htmlentities($result->candidate);?></td>
<?php } ?>
<td class="center"align="left"><?php echo htmlentities($result->Total);?></td>
</tbody>
</table>
Add total while iterating through rows and display it outside the loop, Sample code is given below
$sql = "SELECT * FROM tblexam WHERE city='UP'";
$result = $conn->query($sql);
$numRows = $result->num_rows;
if ($numRows> 0) {
$total = 0;
echo '<table border="1" cellpadding="5" cellspacing="0">';
echo '<tr>';
echo '<th>state</th>';
echo '<th>city</th>';
echo '<th>candidate</th>';
echo '</tr>';
while($row = $result->fetch_assoc()) {
$total+=$row['candidate'];
echo '<tr>';
echo '<td>'.$row['city'].'</td>';
echo '<td>'.$row['state'].'</td>';
echo '<td>'.$row['candidate'].'</td>';
echo '</tr>';
}
echo '<tr>';
echo '<td>Total</td>';
echo '<td> </td>';
echo '<td>'.$total.'</td>';
echo '</tr>';
echo '<table>';
}
Before you start looping the data you can create a variable which you set to 0, inside the loop you can add the result's total to this variable, after the loop, the variable will contain the grand total:
$total = 0;
foreach($results as $result) {
$total += (int)$result->Total;
...
}
// $total = 1425

PHP - How to use Foreach to turn a list into a column rather than a row of items?

I have a database, and am trying to get a list using PHP with foreach, but the list are returning like this:
RiquelmeMacielLewBrMarcuus
But it like so:
RiquelmeMaciel
LewBr
Marcuus
My code:
<?php
include_once("conexao.php");
$select = "SELECT * FROM usuarios ORDER BY id";
$query = mysqli_query($conn, $select);
$rows = mysqli_fetch_assoc($query);
?>
<?php foreach($rows as $row){
echo '<td class="mdl-data-table__cell--non-numeric name">'.$row['nome'].'</td>';
} ?>
You need to insert table rows to create the rows:
<?php
//Incluindo a conexão com banco de dados
include_once("conexao.php");
$result_usuario = "SELECT * FROM usuarios ORDER BY id";
$resultado_usuario = mysqli_query($conn, $result_usuario);
$resultado = mysqli_fetch_assoc($resultado_usuario);
foreach($resultado_usuario as $teste){
echo '<tr>';
echo '<td class="mdl-data-table__cell--non-numeric name">'.$teste['nome'].'</td>';
echo '<td class="mdl-data-table__cell--non-numeric"></td>';
echo '<td class="mdl-data-table__cell--non-numeric"></td>';
echo '</tr>';
}
Now you just need to add in your variables for 'EMAIL' and 'SENHA'.
The problem in your foreach cycle - for eache element you output tag, but is a table cell tag.
If you want fill first column in your 3-column table, you must do something like this:
<?php foreach($resultado_usuario as $teste){
echo '<tr>';
echo '<td class="mdl-data-table__cell--non-numeric name">'.$teste['nome'].'</td>';
echo '<td>second column</td>';
echo '<td>third column</td>';
echo '</tr>';
} ?>
Your are displaying your data the wrong way, your <td> should be inside <tr> which should be inside a <table>:
<table>
<tr>
<th>Nome</th>
<th>Email</th>
<th>Senha</th>
</tr>
<?php
foreach ($resultado_usuario as $teste){
echo '<tr>';
echo '<td class="mdl-data-table__cell--non-numeric name">'.$teste['nome'].'</td>';
echo '<td class="mdl-data-table__cell--non-numeric email">'.$teste['email'].'</td>';
echo '<td class="mdl-data-table__cell--non-numeric senha">'.$teste['senha'].'</td>';
echo '</tr>';
}
?>
</table>
The data will then be displayed as you wanted it. Have a look at HTML - table.
If you want to change the order of your data from your SQL query, use the ORDER BY ... ASC|DESC.

Creating a table in HTML to display the result of a query in MySQL

I want to create a PHP page to display the results of a query in a MySQL database under the format of a table. By spending quite some time on different forums, I ended with something that is somehow satisfying me but that is strongly affecting the design and the layout of my webpage. Due to the fact that I wrote the code by a test-fail strategy, it is far from being straightforward and I am sure it is possible to shorten and simplify it and, therefore, make it more compatible with the format of my webpage. Could anybody have a look at it and give some suggestions of general interest about how to solve this kind of issues?
<div id="main">
<?php
require_once('../mysqli_connect.php');
$response = $db->query("SELECT * FROM metabolite");
echo '<table align="center" cellspacing="2" cellpadding="5" border = "1">
<tr><td align="center"><b>Metabolites</b></td>
<td align="center"><b>KEGG Id</b></td>
<td align="center"><b>Synonyms</b></td></tr>';
while ($data = $response->fetch())
{
?>
<tr><td align="left">
<?php echo $data['Metabolite_name']; ?></td>
<td align="left">
KEGG: <?php echo $data['Synonyms']; ?></td>
<td align="left">
<?php echo $data['Synonyms']; ?></td>
</tr>
<?php
}
$response->closeCursor();
?>
</div>
I thank you in advance for all your effort and your help.
Tom.
There's no way we can improve the design and layout of your webpage with the code you've given us. What I can do is write 'better' readable code.
<?php
function tableCell($content)
{
echo '<td align="left">'.$content.'</td>';
}
// database access
require_once('../mysqli_connect.php');
// get all records from the metabolite table
$response = $db->query("SELECT * FROM metabolite");
// start main division
echo '<div id="main">';
// start the table
echo '<table align="center" cellspacing="2" cellpadding="5" border = "1">';
// walk through all the metabolite records
while ($data = $response->fetch())
{
// start a row
echo '<tr>';
// create the cells
tableCell($data['Metabolite_name']);
tableCell('KEGG: '.$data['Synonyms']);
tableCell($data['Synonyms']);
// finish a row
echo '</tr>';
}
// close the table
echo '</table>';
// close main division
echo '</div>';
// close query
$response->closeCursor();
But this is not worth much, the output should remain the same.
if ($response->num_rows > 0) {
while($data = $response->fetch_assoc()) {
echo "<tr><td>" . $data["Metabolite_name"]. "</td></tr>" . ;
}
}
else {
echo "0 results";
}

PHP returning a blank page after executing the script

This code was working perfectlty as most of you said. I had a little issue with the path pointing to this script. The problem now is that I am having issues with the hyperlink with the href code line. I have a field in my database that is labled fulltext . I am trying to create a script that allows me display the content of fulltext (echo "{$row['fulltext']}.";) when I click on the Read More button. The hyperlink should be populated with the echo "{$row['title']}.";
What mistake am I making by inserting a href="fulltext.php?=$row['fulltext']
<table>
<?php
$dbhost = 'localhost';
$dbuser = 'myusernm';
$dbpass = 'mypwd';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT title, introtext, created, created_by, catid FROM mydb_items';
mysql_select_db('muslimtimes360');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo '<tr>'; echo '<td>'; echo '<span class="post-date">'; echo "{$row['created']}."; echo '</span>'; echo '</td>'; echo '</tr>';
echo '<tr>';
echo '<td>'; echo '<h2 class="blog-post-title">'; echo "{$row['title']}."; echo '</h2>'; echo '</td>';
echo '</tr>';
echo '<tr>';
echo '<td>'; echo '<p>'; echo "{$row['introtext']}."; echo '</p>'; echo '</td>'; echo '</tr>';
echo '<p>'; echo '<tr>';
echo '<td>'; echo ''; echo '<input type="button" value="Read More" />'; echo ''; echo '</td>';
echo '</tr>';
echo '</div>';
echo '<div class="blog-meta">';
echo '<img src="img/avatar.png" alt="Avatar" />';
echo '<tr>'; echo '<td>'; echo '<h4 class="blog-meta-author">'; echo "{$row['created_by']}."; '</h4>';
echo '<span>'; echo 'Category:'; echo "{$row['catid']}."; echo '</span>'; echo '</td>'; echo '</tr>';
echo '</table>';
}
echo "";
mysql_close($conn);
?>
Please note mysql_fetch_array only need data (array), no need to give MYSQL_ASSOC, because you're conflating MySQL and MySQLi
and
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
Change this
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
to this:
while($row = mysql_fetch_array($retval))
and inside while just use:
echo $row['created'];
No need of use like this echo "{$row['created']}".
You are Using Old Mysql Syntax Which is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0.
If you are using Latest version of PHP then your code will not Work.Change the appropriate Syntax and Try again.
Try remove the first line table and put inside
example
while($row = mysql_fetch_array($retval))
{
echo '<table>';
I have tried to run your code with only adjusted connection credentials and table/column names and it works fine (using php 5.5 and php 5.3).
Isn't possible there is no record in the database? Another possibility could be some typo.
Edit: Also you have only one table opening tag while as many closing tags as there is records present. Try to inspect source code of the 'blank page'.
Edit2: Try running this snippet instead of your former code and let us know what happens:
<?php
// connection string constants
define('DSN', 'mysql:dbname=muslimtimes360;host=localhost');
define('USER', 'myusernm');
define('PASSWORD', 'mypwd');
// pdo instance creation
$pdo = new PDO(DSN, USER, PASSWORD);
// query preparation
$stmt = $pdo->query("
SELECT title, introtext, created, created_by, catid
FROM mydb_items
");
// fetching results
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// if this returns 0 then it means no records are present
echo count($result) . "\n";
// the loop should print valid table
foreach ($result as $index => $row) {
if ($index == 0) echo '<table>';
echo <<<HTM
<tr>
<td>
<span class="post-date">{$row['created']}</span>
</td>
</tr>
<tr>
<td>
<h2 class="blog-post-title">{$row['title']}</h2>
</td>
</tr>
<tr>
<td>
<p>
{$row['introtext']}
</p>
</td>
</tr>
<tr>
<td>
<p>
<input type="button" value="Read More" />
</p>
</td>
</tr>
<tr>
<td>
<div class="blog-meta">
<img src="img/avatar.png" alt="Avatar" />
<h4 class="blog-meta-author">{$row['created_by']}</h4>
<span>Category: {$row['catid']}</span>
</div>
</td>
</tr>
HTM;
if ($index == (count($result)-1)) echo '</table>';
}

PHP MYSQL, How to show records in four columns ,

Here is my code the records shows in four columns but if my records is blank it shows three balng images, any suggestions?
$query = mysql_query("SELECT * from rbf_events_images where event_id='".$_GET['id']."'");
echo '<table border="1">';
if(count(mysql_num_rows($query)>0)):
$tropentags='<tr>';
$troclosingtags='</tr>';
$formTags="";
$tdTags="";
$count=1;
while($row = mysql_fetch_array($query)){
$tdTags.='<td align="left" valign="middle" class="td" >$row['image']</td>';
if ($count>3)
{
$formTags.=$tropentags.$tdTags.$troclosingtags;
$tdTags="";
$count=0;
}
$count=$count+1;
}
if ($count>0)
{
for($i = 1; $i <= (4-$count) ; $i++)
{
$tdTags.='<td align="left" valign="middle" class="td" >$row['image']</td>';
}
$formTags.=$tropentags.$tdTags.$troclosingtags;
}
echo $formTags;
endif;
Thanks for your help!really appreciated!
I noticed that on lines like this one:
$tdTags.='<td align="left" valign="middle" class="td" >$row['image']</td>';
You are delimiting the string with single quotes ('), and you are also trying to embed a variable in the string that uses single quotes. I'm not sure how you did not get compile errors for that. I would switch to:
$tdTags= '<td align="left" valign="middle" class="td">' . $row['image'] . '</td>';
Here's what I usually do to put records in columns:
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * from rbf_events_images where event_id='$id'");
echo '<table border="1"><tbody><tr>';
if (mysql_num_rows($query) > 0) {
$count = 0;
while ($row = mysql_fetch_array($query)) {
if ($count && $count % 4 == 0) echo '</tr><tr>';
echo '<td align="left" valign="middle" class="td">'.$row['image'].'</td>';
$count++;
}
}
echo '</tr></tbody></table>';

Categories