display data from SQL database into php/ html table [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a database on MySQL and I want to display one of my SQL tables on a HTML or PHP table. I have searched online and cannot implement this feature. Could someone please help me with the coding?
database = 'hrmwaitrose'
username = 'root'
host = 'localhost'
There is no password.
I would like to display the data from the "employee" table.

PHP provides functions for connecting to a MySQL database.
$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('hrmwaitrose');
$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . htmlspecialchars($row['name']) . "</td><td>" . htmlspecialchars($row['age']) . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
In the while loop (which runs every time we encounter a result row), we echo which creates a new table row. I also add a to contain the fields.
This is a very basic template. You see the other answers using mysqli_connect instead of mysql_connect. mysqli stands for mysql improved. It offers a better range of features. You notice it is also a little bit more complex. It depends on what you need.
Please note that "mysql_fetch_array" is now deprecated since PHP 5.5.0, and it was removed in PHP 7.0.0. So please take a look in "mysqli_fetch_array()" instead.

Here's a simple function I wrote to display tabular data without having to input each column name:
(Also, be aware: Nested looping)
function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
$output .= '<tr>';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
UPDATED FUNCTION BELOW
Hi Jack,
your function design is fine, but this function always misses the first dataset in the array. I tested that.
Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.
The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.
You can avoid that by moving the if condition above the second foreach loop like this:
function display_data($data) {
$output = "<table>";
foreach($data as $key => $var) {
//$output .= '<tr>';
if($key===0) {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= "<td>" . $col . '</td>';
}
$output .= '</tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
else {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
}
$output .= '</table>';
echo $output;
}
Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016
and another update that removes redundant code blocks that hurt maintainability of the code.
function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
$output .= '<tr>';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}

refer to http://www.w3schools.com/php/php_mysql_select.asp .
If you are a beginner and want to learn, w3schools is a good place.
<?php
$con=mysqli_connect("localhost","root","YOUR_PHPMYADMIN_PASSWORD","hrmwaitrose");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM employee");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName']; //these are the fields that you have stored in your database table employee
echo "<br />";
}
mysqli_close($con);
?>
You can similarly echo it inside your table
<?php
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['FirstName'] . "</td><td> " . $row['LastName'] . "</td></tr>"; //these are the fields that you have stored in your database table employee
}
echo "</table>";
mysqli_close($con);
?>

Look in the manual http://www.php.net/manual/en/mysqli.query.php
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!$mysqli->query("SET #a:='this will not work'")) {
printf("Error: %s\n", $mysqli->error);
}
$result->close();
}
$mysqli->close();
?>

Related

Individually displaying stored items in an array

I've been having issues displaying items that i saved from my database in an array. My table has two columns for 'name' and 'details'. I successfully retrieved them using mySQLi and stored in an array but instead of displaying all the columns at once, I want to place them at different places on my webpage. eg
<p>$Name1: $Details1</p>. then on another section of the same page
<p>$Name2: $Details2</p>. This is my code:
<?php
include ("config/database.php");
$mysqli = new mysqli($host, $user, $passwd, $database);
if ($mysqli-> connect_errno){
printf("Connect failed: %s\n",$mysqli-> connect_error);
exit();
}
$query = "SELECT name, details FROM recent_properties LIMIT 3";
if($result = $mysqli->query($query)){
printf("%s: %s<br>", $row["name"], $row["details"]);
$result->free();
}
$mysqli->close();
?>
Did you try like this.Make use of loop. To display all the records.
$query = "SELECT name, details FROM recent_properties LIMIT 3";
$result = $mysqli->query($query);
if($result->num_rows()>0)
{
while($row = $result->fetch_assoc())
{
printf("%s: %s<br>", $row["name"], $row["details"]);
}
}
$mysqli->close();
$query = "SELECT name, details FROM recent_properties";
$result = $mysqli->query($query);
if($result->num_rows()>0)
{
$html = "<table>";
$html .= '<tr><th>Name</th><th>Details</th></tr>';
while ($row = $result->fetch_assoc()) {
$html .= '<tr>';
$html .= '<td>' . $row["name"] . '<td>';
$html .= '<td>' . $row["details"] . '<td>';
$html .= '</tr>';
}
$html .= "</table>";
echo $html;
}
$mysqli->close();
this is the simplest way to create HTML content from data
in your case you can do some thing like this
if ($result->num_rows() > 0) {
$dataArray = [];
while ($row = $result->fetch_assoc()) {
$dataArray[$row["name"]] = $row["details"];
}
}
and then use the array in your HTML
<body>
<p><?php echo 'a: ' . $arrayData['a'] ?></p>
<p><?php echo 'b: ' . $arrayData['b'] ?></p>
<p><?php echo 'c: ' . $arrayData['c'] ?></p>
</body>
You need to loop through your $result and fetch an associative array:
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["name"], $row["details"]);
}
EDIT:
while ($row = $result->fetch_assoc()) {
echo '<p>'.$Name1.': '.$Details1.'</p>';
// Whatever else in this section
// You can even break out of PHP and then
// get back into PHP again if you have a lot of HTML.
}

How to remove selected columns from dynamically generated html-table?

I have an SQL-database where I read out data that are then shown in a dynamically generated html-table. Here is my code that works fine:
$sql = "SELECT $selection FROM $tabelle WHERE $masterarray";
$result = mysqli_query($db, $sql) or die("Invalid query");
$numrows = mysqli_num_rows($result);
$numcols = mysqli_num_fields($result);
$field = mysqli_fetch_fields($result);
if ($numrows > 0) {
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
echo "<th>" . $field[$x]->name . "</th>";
}
echo "</tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) {
echo "<td>" . $row[$k] . "</td>"; //Prints the data
}
$nr = $nr + 1;
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
}
mysqli_close($db);
Now, I want to remove specific columns (e.g. those, which are empty or those, which are not that interesting for the user, who makes the request).
I tried it with unset($field[$variable]), however, it didn't work. In addition, the values (if there are any), should be removed, too.
can let mysql filter them out for you,
$sql = "SELECT $selection FROM $tabelle WHERE $masterarray AND LENGTH($selection) > 0";
-- http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_length
Always format the array before you print it. Try to remove the specific columns from the $field array before you echo the HTML and then print the final table. Once the HTML code is echoed in PHP you won't be able to remove it without the use of JavaScript.
You can check against the $field[$x]->name variable and use continue to skip the column.
<?php
// DataBase Config - http://php.net/manual/pt_BR/pdo.construct.php.
$dsn = 'mysql:host=localhost;dbname=test';
$usr = 'root';
$pwd = '';
try { // try to connect in database.
$pdo = new PDO($dsn, $usr, $pwd);
} catch (PDOException $e) { // if there is error in the connection.
die('Connection failed: ' . $e->getMessage());
}
// Prepare Statement and execute - http://php.net/manual/pt_BR/pdo.prepare.php.
$stm = $pdo->prepare('select id, weight, color, name from product');
$stm->execute();
// Get ALL rows - Object.
$rows = $stm->fetchAll(PDO::FETCH_OBJ);
// Print Rows.
//echo '<pre>'.print_r(rows, true).'</pre>';
// Check $row;
if (count($rows)) {
// Order and Display Cols.
$colsDisplay = [
'id' => 'ID Product',
'name' => 'Name',
'weight' => 'Weigth'
];
// Table.
$html = '<table border="1">';
$html .= "\n <thead>";
$html .= "\n <tr>";
$html .= "\n <th bgcolor='#eee'>Row</th>";
$html .= "\n <th>". implode("</th>\n <th>", $colsDisplay) ."</th>";
$html .= "\n </tr>";
$html .= "\n </thead>";
$html .= "\n <tbody>";
// Loop ROWS.
foreach ($rows as $key => $val) {
$html .= "\n <tr>";
$html .= "\n <td bgcolor='#eee'>". $key ."</td>";
// Loop COLS to display.
foreach ($colsDisplay as $thKey => $thVal) {
$html .= "\n <td>". $val->$thKey ."</td>";
}
$html .= "\n </tr>";
}
$html .= "\n".' </tbody>';
$html .= "\n".'</table>';
echo $html;
}
In order to know that a column is empty, you should check the whole column. There are different ways to do it, one of them could be investigating which of them are empty and then only using those that aren't empty. Something like this:
<?php
// ...
$q = "SELECT SUM(LENGTH(my_first_column)) col_0, SUM(LENGTH(my_second_column)) col_1, ..., SUM(LENGTH(my_11th_column)) col_10 FROM $tabelle WHERE $masterarray";
// ... execute query and return results in $nonEmpty
$nonEmpty = array();
foreach($row as $columnIndex) {
if ($row[$columnIndex] > 0) {
$nonEmpty[] = $columnIndex;
}
}
// ... now go through results and print only cols with at least one row with lenght > 0 i.e. non empty
$len = 11;
$rowHTML = "<tr>";
while ($row = mysqli_fetch_array($result)) {
for ($i = 0; $i < $len; ++$i) {
$rowHTML = '';
if (!in_array($i, $nonEmpty)) {
$rowHTML .= '<td>' . $row[$i] . '</td>';
}
$rowHTML .= "</tr>\n";
}
}
// ...
This chunk of code will remove columns with ALL empty values. If you have at least one cell in the column with some value, you'll see the column in your result.
The code isn't optimized - it's just a rough idea. But it's a starting point.

PHP problems getting data from table in mysql... only showing column names as data

I tried this but didn't work for me...I mean I am getting my table and the row count is Correct. But when I use $row['ColumnName']... I keep getting the ACTUAL name of the column and not the data itself.
If I add more rows of data to the table, I get the row count up but the data is still the same. Only Column names.
Anyone has had this issue? and how to solve it?
php version: 5.3 and mysql version: 5.5
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('employeedb');
$query = "SELECT * FROM employee"
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>";
//$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
mysql_ is deprecated, here is some code in PDO.
//Open PDO connection
try {
$db = new PDO("mysql:dbname={'employeedb'}; host={'localhost'}", 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $Exception) {
echo "There was an error.";
}
//Query prep
$query = $db->prepare("
SELECT *
FROM employee
");
//Query execution; try to use prepared statements always
$query->execute();
//create string $output
$output = "<table>";
//for rows of indeterminable quantity, use foreach()
foreach($query as $table) {
//append to $output
$output .= "<tr><td>";
$output .= htmlspecialchars($table["name"]);
$output .= "</td><td>";
$output .= htmlspecialchars($table["age"]);
$output .= "</td></tr>";
}
$output .= "</table>";
//print $output
echo $output;
//close PDO connection
$db = null;
As an aside, make sure to escape all output by using htmlspecialchars(). I would also consider having some kind of try/catch complex to ensure error handling is done correctly and pertinent info isn't revealed to the user.
Oh, looks like you solved it. If you're working within an undefined amount of rows, instead of using a while() loop, consider a foreach() loop instead.
can u try using numeric indexes than coloumn name. like shown below
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
}
Try this:
$db = new PDO ('localhost', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM employee"
$statement = $db->prepare($query);
$statement->execute();
echo '<table>';
foreach($statement as $row){
echo '<tr>';
echo '<td>', $row['name'],'</td>';
echo '<td>',$row['age'],'</td>';
echo '</tr>';
}
echo '</table>';

Too Many Connections; db connect in a function

I'm currently updating my PHP knowledge and I've stumbled upon a problem whilst grabbing data from my database.
The problem I have in itself could probably be sorted with the max_connection setting (yes, I've searched around), but I believe it might be a work-around, since I don't want to change base settings, if not so needed.
I have three "steps" in my little "ladder";
My main is a ladder, every ladder has one (or more) step and every step has one (or more) modules.
So what I'm trying to do is a function that retrieves all of these and shows them. Now, every function has a connection to my database; where the function runs its query and then closes. My first clue was to close the database between every function, which I did - but since I'm retrieving my code "all at once", this doesn't work (see code).
How would I go about making one database connection (maybe in a function) and calling it once, and then retrieving all the information, without opening new connections?
I hope you have all information required to answer my questions, and I hope I'm posting this in a stack overflow way.
Thank you in advance.
P.S: Dunno if I used this code tool right, it looks structured, but it doesn't have highlights?
CODE:
<?php
echo displayResult();
function displayResult() {
$db = new mysqli ('localhost', 'website', 'dog', 'nplus');
$sql = 'SELECT * FROM ladders';
$result = $db->query($sql);
$r = '';
$r .= '<table>';
while ($row = $result->fetch_object()) {
$r .= '<tr>';
$r .= '<td>' . htmlspecialchars($row->ladderID) . '</td>';
$r .= '<td>' . htmlspecialchars($row->ladderName) . '</td>';
$r .= '<td>' . htmlspecialchars($row->created) . '</td>';
$r .= displayAssociateStep($row->ladderID);
$r .= '<tr><td>&nbsp</td></tr>';
}
$r .= '</table>';
$db->close();
return $r;
}
function displayAssociateStep($ladderID) {
$r = '';
$db = new mysqli ('localhost', 'website', 'dog', 'nplus');
$sql = 'SELECT * FROM steps WHERE ladderID = '. $ladderID ;
$result = $db->query($sql);
$r = '';
while ($row = $result->fetch_object()) {
$r .= '<tr>';
$r .= '<td></td>';
$r .= '<td></td>';
$r .= '<td>' . htmlspecialchars($row->stepName) . '</td>';
$r .= '<td>' . htmlspecialchars($row->created) . '</td>';
$r .= '</tr>';
}
$db->close();
return $r;
}
?>
You only need to connect to the database once, and pass it around as an argument, like so:
<?php
function displayResult($db) {
$sql = "
SELECT *
FROM ladders
";
$result = $db->query($sql);
// ADD ERROR CHECKING HERE
// What happens if the query fails?
$r = '<table>';
while ($row = $result->fetch_object()) {
$r .= '<tr>';
$r .= '<td>' . htmlspecialchars($row->ladderID) . '</td>';
$r .= '<td>' . htmlspecialchars($row->ladderName) . '</td>';
$r .= '<td>' . htmlspecialchars($row->created) . '</td>';
$r .= '</tr>';
$r .= displayAssociateStep($db, $row->ladderID);
$r .= '<tr><td colspan="3"> </td></tr>';
}
$r .= '</table>';
return $r;
}
function displayAssociateStep($db, $ladderID) {
// Are you 100% certain $ladderID is always safe to use in a query?
// Does it need escaping?
$sql = "
SELECT *
FROM steps
WHERE ladderID = $ladderID
";
$result = $db->query($sql);
// ADD ERROR CHECKING HERE
// What happens if the query fails?
$r = '';
while ($row = $result->fetch_object()) {
$r .= '<tr>';
$r .= '<td></td>';
$r .= '<td>' . htmlspecialchars($row->stepName) . '</td>';
$r .= '<td>' . htmlspecialchars($row->created) . '</td>';
$r .= '</tr>';
}
return $r;
}
// Connect once
$db = new mysqli ('localhost', 'website', 'dog', 'nplus');
// Pass the connection in as an argument
echo displayResult($db);
// Close the connection
$db->close();
I would say... pass the $db variable you got in displayResult to displayAssociateStep, as an added parameter. Then you don't need to open/close connexion in displayAssociatesStep anymore.
Is it what you want to do?

How to echo out table rows from the db (php)

i want to echo out everything from a particular query. If echo $res I only get one of the strings. If I change the 2nd mysql_result argument I can get the 2nd, 2rd etc but what I want is all of them, echoed out one after the other. How can I turn a mysql result into something I can use?
I tried:
$query="SELECT * FROM MY_TABLE";
$results = mysql_query($query);
$res = mysql_result($results, 0);
while ($res->fetchInto($row)) {
echo "<form id=\"$row[0]\" name=\"$row[0]\" method=post action=\"\"><td style=\"border-bottom:1px solid black\">$row[0]</td><td style=\"border-bottom:1px solid black\"><input type=hidden name=\"remove\" value=\"$row[0]\"><input type=submit value=Remove></td><tr></form>\n";
}
$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!! Check summary get row on array ..
echo "<tr>";
foreach ($row as $field => $value) { // I you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>"; // I just did not use "htmlspecialchars()" function.
}
echo "</tr>";
}
echo "</table>";
Expanding on the accepted answer:
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("<br>{$query}<br>*** {$err} ***<br>");
}
}
...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first_row) {
$first_row = false;
// Output header row from keys.
echo '<tr>';
foreach($row as $key => $field) {
echo '<th>' . htmlspecialchars($key) . '</th>';
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo("</table>");
Benefits:
Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.
Shows field names as a header row of table.
Shows how to get both column name ($key) and value ($field) for each field, as iterate over the fields of a row.
Wrapped in <table> so displays properly.
(OPTIONAL) dies with display of query string and mysql_error, if query fails.
Example Output:
Id Name
777 Aardvark
50 Lion
9999 Zebra
$result= mysql_query("SELECT * FROM MY_TABLE");
while($row = mysql_fetch_array($result)){
echo $row['whatEverColumnName'];
}
$sql = "SELECT * FROM YOUR_TABLE_NAME";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!!
echo "<tr>";
foreach ($row as $field => $value) { // If you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
In PHP 7.x You should use mysqli functions and most important one in while loop condition use "mysqli_fetch_assoc()" function not "mysqli_fetch_array()" one. If you would use "mysqli_fetch_array()", you will see your results are duplicated. Just try these two and see the difference.
Nested loop to display all rows & columns of resulting table:
$rows = mysql_num_rows($result);
$cols = mysql_num_fields($result);
for( $i = 0; $i<$rows; $i++ ) {
for( $j = 0; $j<$cols; $j++ ) {
echo mysql_result($result, $i, $j)."<br>";
}
}
Can be made more complex with data decryption/decoding, error checking & html formatting before display.
Tested in MS Edge & G Chrome, PHP 5.6
All of the snippets on this page can be dramatically reduced in size.
The mysqli result set object can be immediately fed to a foreach() (because it is "iterable") which eliminates the need to maked iterated _fetch() calls.
Imploding each row will allow your code to correctly print all columnar data in the result set without modifying the code.
$sql = "SELECT * FROM MY_TABLE";
echo '<table>';
foreach (mysqli_query($conn, $sql) as $row) {
echo '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
echo '</table>';
If you want to encode html entities, you can map each row:
implode('</td><td>' . array_map('htmlspecialchars', $row))
If you don't want to use implode, you can simply access all row data using associative array syntax. ($row['id'])

Categories