I want my PHP to create ONE table, but it creates SEVERAL - php

I need to create a table via php with data from my mysql server. I've managed to establish a connection, and I can create a table, but my problem is that it creates a table for each of the rows, whereas I want one unified. This is my code:
$sql = 'SELECT navn, institution, klip FROM parkeringsdata';
mysqli_select_db($conn , 'parkeringsdb');
$retval = mysqli_query( $conn , $sql );
echo "<br><br><br>";
if(! $retval ) {
die('Could not get data: ' . mysqli_error());
}
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
echo "<table class='content info'>
<tr>
<td>Navn</td>
<td>Institution</td>
<td>Klip</td>
<td>Rediger</td>
<td>Slet</td>
</tr>
<tr>
<td>".$row["navn"]."</td>
<td>".$row["institution"]."</td>
<td>".$row["klip"]."</td>
<td><button type='button'>Rediger</button></td>
<td><button type='button'>Slet</button></td>
</tr></table><br>";
}
echo "Fetched data successfully\n";
mysqli_close($conn);
EDIT: Thanks for all the quick responses, it's solved now and I see where I made it a rookie mistake. It's for a school assignment and we'd been wracking our brains here :)

You'll want to extract the "", "" and your table-header definition out of the for loop, so it will only be executed once.
And: Creating tables this way is easy to do, but leads to error-prone & difficult to maintain code.
It's okay to learn it step by step.
But most likely you'll want to switch to a templating engine (on client or server side, your&your applications choice) sooner or later.

$table = "<table class='content info'>";
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
$table .= "
<tr>
<td>Navn</td>
<td>Institution</td>
<td>Klip</td>
<td>Rediger</td>
<td>Slet</td>
</tr>
<tr>
<td>".$row["navn"]."</td>
<td>".$row["institution"]."</td>
<td>".$row["klip"]."</td>
<td><button type='button'>Rediger</button></td>
<td><button type='button'>Slet</button></td>
</tr>";
}
$table .= "</table><br>";
You have table start and end tags inside foreach loop.

Echo table outside the while loop
$sql = 'SELECT navn, institution, klip FROM parkeringsdata';
mysqli_select_db($conn , 'parkeringsdb');
$retval = mysqli_query( $conn , $sql );
echo "<br><br><br>";
if(! $retval ) {
die('Could not get data: ' . mysqli_error());
}
echo "<table class='content info'>";
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
echo "<tr>
<td>Navn</td>
<td>Institution</td>
<td>Klip</td>
<td>Rediger</td>
<td>Slet</td>
</tr>
<tr>
<td>".$row["navn"]."</td>
<td>".$row["institution"]."</td>
<td>".$row["klip"]."</td>
<td><button type='button'>Rediger</button></td>
<td><button type='button'>Slet</button></td>
</tr>";
}
echo "</table><br>";
echo "Fetched data successfully\n";
mysqli_close($conn);

Related

How do I display different table from 1 table? Like each table has unique code

This are my db table:
But my query only get 1 row for each table like this:
As you can see, there are 2 tables for 1003 because it has 2 rows. It should be only one (1) table of 1003 with 2 rows. How do I fix this? EXPECTED RESULT:
// Attempt select query execution
$query = "SELECT model, brand_code FROM smartphone GROUP BY model";
if($result = mysqli_query($db, $query))
{
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<?php echo $row["brand_code"]?>
<table id="table_stock" class="">
<thead>
<tr>
<th>Model</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $row["model"]?></td>
</tr>
</tbody>
</table><br>
<?php
}
/// Free result
mysqli_free_result($result);
}
else
{
echo "<td class='no_record' colspan='7'>No records found.</td>";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
You have at least 5 problems here,
[edit: problem 1 removed & changed sample based on extended answer]
Inside your while { ... } loop, you're printing an entire table, when you should only be printing the <tr>...</tr> part there. This is what causes additional table(s).
And 3rd problem: your "no_record" line is a loose <td>. Not only isn't it inside the table (which is covered in problem #2), it's also not wrapped with a <tr>.
4th problem: You're randomly printing the echo $row["brand_code"] outside of the table.
5th problem: you're printing raw data from the database as if it is valid html, it more than likely is not. it has to be probably encoded with htmlentities/htmlspecialchars.
Quick & dirty fixed version:
function tableOpen($row) {
printf( '<h1>%s</h1>', htmlentities($row["brand_code"]) );
echo '<table id="table_stock" class="">';
echo '<thead>';
echo '<tr>';
echo '<th>Model</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
}
function tableClose() {
echo '</tbody>';
echo '</table><br>';
}
// Attempt select query execution
$query = "SELECT model, brand_code FROM smartphone ORDER BY brand_code";
$lastBrand = null;
if ($result = mysqli_query($db, $query)) {
if (mysqli_num_rows($result) > 0) {
if ($lastBrand !== $row["brand_code"] && !is_null($lastBrand)) tableClose();
if ($lastBrand !== $row["brand_code"]) tableOpen($row);
$lastBrand = $row["brand_code"];
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
printf( '<td>%s</td>', htmlentities($row["model"]) );
echo '</tr>';
}
tableClose();
/// Free result
mysqli_free_result($result);
} else {
echo '<p class="no_record">No records found.</p>';
}
} else {
echo "ERROR: Not able to execute \$query: <br>" . htmlentities($query) . '<br>' . htmlentities(mysqli_error($link));
}
you need additional loop. Also in the first query you need to use group by codes.
$query = "SELECT model, brand_code FROM smartphone GROUP BY brand_code";
if($result = mysqli_query($db, $query))
{
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<?php echo $row["brand_code"]?>
<table id="table_stock" class="">
<thead>
<tr>
<th>Model</th>
</tr>
</thead>
<tbody>
<?php
if ($result1 = mysqli_query($db, "SELECT DISTINCT model, brand_code FROM smartphone WHERE brand_code={$row["brand_code"]}"))
{
while ($row1 = mysqli_fetch_array($result1))
{
// get count for each model within brand_code
$cnt = ($result2 = mysqli_query($db, "SELECT COUNT(*) AS cnt FROM smartphone WHERE brand_code={$row["brand_code"]} AND model='{$row1["model"]}'")) && ($row2 = mysqli_fetch_array($result2)) ? $row2["cnt"] : "---";
?>
<tr>
<td><?php echo $row1["model"] ({$cnt})?></td>
</tr>
<?php
}
mysqli_free_result($result1);
}
?>
</tbody>
</table><br>
<?php
}
/// Free result
mysqli_free_result($result);
}
else
{
echo "<td class='no_record' colspan='7'>No records found.</td>";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

Why mySQL table won't export properly as HTML table

I use bootstrap 3 template and connect to a mysql database, sort the table and export some datas as HTML table in order to display it on bootstrap webpage.
Here is the mySQL look like :
The following code won't get expected results:
<div class="well">
<?php
//MySQL Database Connect
include '/includes/dbconnect.php';
$result = mysqli_query($conn,"SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");
if(mysqli_num_rows($result) >= 1) {
echo '<table class="table table-striped table-bordered table-hover">';
echo "<tr><th>ID</th><th>NAME:</th><th>EPOCH</th></tr>";
while($row = mysqli_fetch_array($results)) {
echo "<tr><td>";
echo $row['ID'];
echo "</td><td>";
echo $row['NAME'];
echo "</td><td>";
echo $row['NEXT_EVENT'];
echo "</td></tr>";
}
echo "</table>";
}
?>
</div> <!-- well -->
dbconnect.php :
<?php
$localhost="xxx.xx.xxx.com";
$username="dboxxxxxxx";
$password="xxxxxx";
$database="dbxxxxxx";
$conn = mysqli_connect($localhost,$username,$password,$database);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
?>
original page link can be found here : http://s529471052.onlinehome.fr/bs3/gpio/dyntable.htm
Its just a simple typo
$result = mysqli_query($conn,"SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");
if(mysqli_num_rows($result) >= 1) {
echo '<table class="table table-striped table-bordered table-hover">';
echo "<tr><th>ID</th><th>NAME:</th><th>EPOCH</th></tr>";
//while($row = mysqli_fetch_array($results)) {
^^^^^^^^
while($row = mysqli_fetch_array($result)) {
While testing Add
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); `
to the top of your script. This will force any mysqli_ errors to
generate an Exception that you can see on the browser and other errors will also be visible on your browser.
Answer for additional info provided in a comment
From your comment below, it appears you are trying to run PHP code from a web page with a .htm extension. That wont work unless you have configured Apache to do this
Change the web page file name to have a .php extension and then Apache will pass the PHP code to the PHP interpreter for compilation and execution.
$result = mysqli_query($conn,"SELECT ID, NAME, NEXT_EVENT FROM webpilot ORDER BY NEXT_EVENT ASC");
$table = '<table>
<tr>
<th>ID</th>
<th>NAME</th>
<th>EPOCH</th>
</tr>';
if($result ) {
while ($row = mysqli_fetch_assoc($result)) {
$table .= '<tr>
<td>'. $row['ID'] .'</td>
<td>'. $row['NAME'] .'</td>
<td>'. $row['NEXT_EVENT'] .'</td>
</tr>';
}
} else {
$table .= '<tr><td colspan="3">No date found</td></tr>';
}
$table .= '</table>';
echo $table;
Try this, This will help for your requirement.
I'm assuming that your connection to the database is OK (though the given page link suggests otherwise).
It seems the table is not exporting properly because $result was misspelled as $results in the code segment printing the data rows: $row = mysqli_fetch_array($results).
Try the modification below (also refactored for better readability):
<div class="well">
<?php
//MySQL Database Connect
include '/includes/dbconnect.php';
$result = mysqli_query($conn,"SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");
if(mysqli_num_rows($result) >= 1)
{
echo '<table class="table table-striped table-bordered table-hover">';
echo "<tr><th>ID</th><th>NAME:</th><th>EPOCH</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>$row['ID']</td>";
echo "<td>$row['NAME']</td>";
echo "<td>$row['NEXT_EVENT']</td>";
echo "</tr>";
}
echo "</table>";
}
?>
</div> <!-- well -->
Also, you may want to check that $results and $row contain the expected data in the expected formats using print_r($results) and print_r($row).

Re-factoring this mysql table display code

I'm not wholly proficient with PHP but I'm having a few problems echoing a gathered value from a MySQL query function.
I believe I know where the problem lies but I'm not competent enough to fix it, if you could please help it would be appreciated.
PHP Function (Works perfectly).
<?php
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT Name, Role, Salary FROM `users-table`';
mysql_select_db('user_records');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "--------------------------------<br>",
"Name: {$row['Name']} <br> ".
"Role: {$row['Role']} <br> ".
"Salary : {$row['Salary']} <br> ".
"--------------------------------<br>";
}
mysql_close($conn);
?>
This displays the data perfectly! However I'm now trying to include this in a nicely formatted HTML table. (Which is why I'm closing the php tag above).
I'm then trying to use a table like this:
<table >
<tr>
<td>
<?php echo $row['Name'] ?>
</td>
....
It outputs nothing, - I think this problem is caused because I close the first function and then try to reference $row and it doesn't know what to do...?
I think I need to tap in to while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
How can I re-factor this so that I can echo content from the above function to my table?
You didn't write the code you tried, but here is something functional:
$link = mysqli_connect("myhost", "myuser", "mypassw", "mybd");
echo "<table>";
while ($row = mysqli_fetch_array($link, $retval, MYSQL_ASSOC)) {
echo "
<tr>
<td>{$row['Name']}</td>
<td>{$row['Role']}</td>
<td>{$row['Salary']}</td>
</tr>
";
}
echo "</table>";
PS: Since MySQL is deprecated, I replaced your code with MySQLi, and I suggest you do the same :)
As #zessx said, yous should use MySQLi or PDO.
anyway to answer to your question, you have to change the loop in your php code from
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "--------------------------------<br>",
"Name: {$row['Name']} <br> ".
"Role: {$row['Role']} <br> ".
"Salary : {$row['Salary']} <br> ".
"--------------------------------<br>";
}
to
echo '<table>';
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo " <tr>" .
" <td>Name: {$row['Name']}</td>".
" <td>Role: {$row['Role']}</td>".
" <td>Salary : {$row['Salary']}</td>".
" </tr>";
}
echo '</table>';

Display result from database in two columns

EDIT: This is what I am trying to achieve: http://i.imgur.com/KE9xx.png
I am trying to display the results from my database in two columns. I'm a bit new to PHP so I haven't the slightest clue on how to do this. Can anybody help me with this? Thanks in advance.
Here is my current code:
include('connect.db.php');
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM todo ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table width='415' cellpadding='0' cellspacing='0'>";
// set table headers
echo "<tr><td><img src='media/title_projectname.png' alt='Project Name' /></td>
<td><img src='media/title_status.png' alt='Status'/></td>
</tr>";
echo "<tr>
<td><div class='tpush'></div></td>
<td> </td>
</tr>"
while ($row = $result->fetch_object())
{
echo "<tr>";
echo "<td><a href='records.php?id=" . $row->id . "'>" . $row->item . "</a></td>";
echo "<td>" . $row->priority . "</td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
A good idea would be storing your data into a simple array and then display them in a 2-columned table like this:
$con = mysql_connect('$myhost', '$myusername', '$mypassword') or die('Error: ' . mysql_error());
mysql_select_db("mydatabase", $con);
mysql_query("SET NAMES 'utf8'", $con);
$q = "Your MySQL query goes here...";
$query = mysql_query($q) or die("Error: " . mysql_error());
$rows = array();
$i=0;
// Put results in an array
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
$i++;
}
//display results in a table of 2 columns
echo "<table>";
for ($j=0; $j<$i; $j=$j+2)
{
echo "<tr>";
echo "<td>".$row[$j]."</td><td>".$row[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
<table>
<tr>
<td>ProjectName</td>
<td>Status</td>
<td>ProjectName</td>
<td>Status</td>
</tr>
<?php
while($row = $result->fetch_object()) {
echo "<tr>";
echo "<td>".$row->ProjectName."</td>";
echo "<td>".$row->Status."</td>";
echo "<td>".$row->ProjectName."</td>";
echo "<td>".$row->Status."</td>";
echo "</tr>";
}
?>
</table>
This is the thing on picture. With a bit CSS you can manipulate the tds.
Your function should look similar to this:
$query = "SELECT *
FROM todo
ORDER BY id";
$result = $mysqli->query($query);
while($row = $result -> fetch_array()) {
$feedback .= "<tr>\n<td>" . $row['item'] . "</td><td>" . $row['priority'] . "</td>\n</tr>";
}
return $feedback;
Then, in your HTML have the <table> already setup and where you would normally insert your <td> and <tr> put <?php echo $feedback?> (where $feedback is the assumed variable on the HTML page that retrieves the $feedback from the function). This isn't a complete fix, your code is hard to read, but by starting here, you should be able to continue on the path filling in all the extra information you need for the table, including your CSS.

Fetch information from mysql db using php

Updated script with proper field names. Why isnt this working?
<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bookorama", $con);
$sql="SELECT * FROM customers";
$result = mysql_query($sql); // You actually have to execute the $sql with mysql_query();
echo "<table>"; //start the table
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) //Loop through the results
{
//echo each row of the table
echo "<tr>
<td>$row['customerID']</td>
<td>$row['name']</td>
<td>$row['Aaddress']</td>
<td>$row['city']</td>
</tr>";
}
echo '</table>'; //close out the table
?>
<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bookorama", $con);
$sql="SELECT * FROM customers";
$result = mysql_query($sql); // You actually have to execute the $sql with mysql_query();
echo "<table>"; //start the table
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) //Loop through the results
{
//echo each row of the table
echo "<tr>";
echo "<td>$row['CustomerID']</td>";
echo "<td>$row['address']</td>";
echo "<td>$row['city']</td>";
echo "</tr>";
}
echo '</table>'; //close out the table
?>
You can mysql_fetch_array or mysql_fetch_assoc to retriever the rows from you query.
For example using mysql_fetch_array:
$result = mysql_query($sql);
echo "<table><tbody>";
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "<tr><td>".$row[0] . "</td><td>" . $row[1] . "</td></tr>";
}
echo "</tbody></table>"
You need to run the query and loop through the results.
You are better off learning from day one about PDO.
And also don't interpolate directly from any user submitted variables (that includes $_POST).
Pretty sure you need to do this when embedding anything more complex than scalars inside double quotes
echo "<tr>
<td>{$row['CustomerID']}</td>
<td>{$row['address']}</td>
<td>{$row['city']}</td>
</tr>";
So whenever you have a more complex var name than "test $var" in quotes, wrap with {} - and even then, it's good practice to wrap scalars too like "test {$var}"

Categories