I have managed to take information from my database of the website, however I have no idea how to present the results in a table and how to style it. I tried putting <table> outside of the whole PHP, clearly did not work. I tried echoing a <table> tag before the result echo and a closing </table> tag after it, but that did not do it. This is the code I am working with:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "onlib";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Takes all the results from the table with genre 5.
$sql = "SELECT name, description, content FROM books WHERE genre='5'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<span style='color:white;'>"."<br> Name: ".$row["name"]."<br> Description: ".$row["description"]."<br> Content: ".$row["content"] ."<br>"."</p>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I am still new in PHP, trying to understand how the whole thing works. Thanks in advance!
<?php
function tableV1 ($row) {
echo '<tr>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>' . $row['description'] . '</td>';
echo '<td>' . $row['content'] . '</td>';
echo '</tr>';
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "onlib";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
?>
Always do Database Connection first, before Outputting anything, that way, you can create custom error message to show instead of a failed database conntection or no content at all.
<style type="text/css">
table {}
tbody {}
td {}
th {}
thead {}
tr {}
</style>
Style is used inside the <head></head> to style the table, CSS it's called.
<table>
<thead>
<th>Name</th>
<th>Description</th>
<th>Content</th>
</thead>
<tbody>
<?php
// Takes all the results from the table with genre 5.
$sql = "SELECT name, description, content FROM books WHERE genre='5'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
tableV1($row);
}
} else {
echo '<tr><td colspan="3">0 results</td></tr>';
}
?>
</tbody>
</table>
Output contents from database.
<?php
$conn->close();
?>
Close database connection in the end. All together:
<?php
function tableV1 ($row) {
echo '<tr>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>' . $row['description'] . '</td>';
echo '<td>' . $row['content'] . '</td>';
echo '</tr>';
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "onlib";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
table {}
tbody {}
td {}
th {}
thead {}
tr {}
</style>
</head>
<body>
<table>
<thead>
<th>Name</th>
<th>Description</th>
<th>Content</th>
</thead>
<tbody>
<?php
// Takes all the results from the table with genre 5.
$sql = "SELECT name, description, content FROM books WHERE genre='5'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
tableV1($row);
}
} else {
echo '<tr><td colspan="3">0 results</td></tr>';
}
?>
</tbody>
</table>
</body>
</html>
<?php
$conn->close();
?>
Try this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "onlib";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Takes all the results from the table with genre 5.
$sql = "SELECT name, description, content FROM books WHERE genre='5'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
echo "<table>";
echo "<thead>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
</thead>";
echo "<tbody>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["description"]."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "onlib";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Takes all the results from the table with genre 5.
$sql = "SELECT name, description, content FROM books WHERE genre='5'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '<table>';
echo '<tr><td>Name</td><td>Description</td><td>Content</td></tr>'
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["name"]."</td><td>".$row["description"]."</td><td>".$row["content"] ."</td></tr>";
}
echo '</table>';
} else {
echo "0 results";
}
$conn->close();
?>
The basic table format is this
for example:
<table>
<tr>
<td>row 1 item 1</td>
<td>row 1 item 2</td>
</tr>
<tr>
<td>row 2 item 1</td>
<td>row 2 item 2</td>
</tr>
</table>
so try:
if ($result->num_rows > 0) {
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["description"]."</td>";
echo "<td>".$row["content"]."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
Try this approach:
[... some HTML header and code ...]
<table>
<thead>
<tr><th>Name</th><th>Description</th><th>Content</th></tr>
</thead>
<tbody>
<?php
[ ... extract something from the database ...]
while($row = $result->fetch_assoc())
{
echo "<tr><td>$row[name]</td><td>$row[description]</td><td>Content</td></tr>\n";
}
}
?>
</tbody>
</table>
[... some HTML footer ...]
Obviously, replace the [...] sections with your own code. The idea is here to use PHP to output the dynamic part of your HTML code, and is the power of PHP combined with HTML.
I try to avoid "echoing" to much HTML in my PHP, but it does work (reference other answers).
Detail: when setting up a <table> you should setup a header section <thead> <tfoot> (if applicable) and body section <tbody>. Ref What is the purpose for HTML's tbody?
Related
I have a Table which Input all the necessary data to do statistics. i now face the issue that i dont know how to add up the values for each colum but that it only adds the values up for each day. and then Displays it in a row or another Table.
this Code is what i use to call out all of the values and insert them into a table
<html>
<head>
<title>Your Home Page</title>
</head><body>
<table border="1">
<tr>
<th>Date</th>
<th>Participant ID</th>
<th>Gender</th>
<th>Hand</th>
<th>Udnder 18</th>
<th>Adult</th>
<th>R</th>
<th>C</th>
<th>L</th>
<th>Cash</th>
<th>Card</th>
<th>Ammount</th>
</tr>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "***";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * FROM table ORDER BY Date ASC";
$result = mysqli_query($mysqli, $sql) or die(mysqli_error());
$datum = '';
while($set = mysqli_fetch_assoc($result)) {
?>
<tr>
<td>
<?php
if ($datum == $set["Date"]) {
echo ' ';
} else {
echo $set["Date"];
}
?>
</td>
<td><?php echo $set["ParticipantID"]; ?></td>
<td><?php echo $set["Gender"]; ?></td>
<td><?php echo $set["Hand"]; ?></td>
<td><?php echo $set["Under18"]; ?></td>
<td><?php echo $set["Adult"]; ?></td>
<td><?php echo $set["r"]; ?></td>
<td><?php echo $set["c"]; ?></td>
<td><?php echo $set["l"]; ?></td>
<td><?php echo $set["Cash"]; ?></td>
<td><?php echo $set["Card"]; ?></td>
<td><?php echo $set["Ammount"]; ?></td>
</tr>
<?php $datum = $set["Date"]; ?>
<?php
}
?>
</table> </body></html>
So for 04-01-2018 for the colum R the total summed up value should be 2. etc.
Thanks for the help.
Kind Regards
Mark
The first way of solving this problem is to use the second MySQL query to get total values for each date. After that create a function printDateTableRow to print each row of the table. Using the mysqli_fetch_assoc($totalMysqliResult) parameter of this function, you can pass values of a row with total values for each new date.
Another way is to use the the WITH ROLLUP group modifier (you can try to write such query by yourself).
Here is the working code for the first way:
<html>
<head>
<title>Your Home Page</title>
</head>
<body>
<table border="1">
<tr>
<th>Date</th>
<th>Participant ID</th>
<th>Gender</th>
<th>Hand</th>
<th>Udnder 18</th>
<th>Adult</th>
<th>R</th>
<th>C</th>
<th>L</th>
<th>Cash</th>
<th>Card</th>
<th>Ammount</th>
</tr>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "***";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * FROM `table` ORDER BY Date ASC";
$result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
$totalMysqliResult = mysqli_query($mysqli, '
SELECT
Date, "" AS ParticipantID, "" AS Gender, "" AS Hand,
SUM(Under18) AS date_total_Under18,
SUM(Adult) AS date_total_Adult, SUM(r) AS date_total_r,
SUM(c) AS date_total_с, SUM(l) AS date_total_l,
SUM(Cash) AS date_total_Cash, SUM(Card) AS date_total_Card,
SUM(Amount) AS date_total_Amount
FROM `table`
GROUP BY Date
ORDER BY Date ASC') or die(mysqli_error($mysqli));
/**
* #param $row
* #param null $dateFieldHeader
*/
function printDateTableRow($row, $dateFieldHeader = null) {
?><tr><?
foreach ($row as $key => $curVal) {
?><td><?
if ($key == 'Date') {
echo $dateFieldHeader == null ? $curVal : $dateFieldHeader;
} else {
echo $curVal;
}
?></td><?
}
?></tr><?
}
$previousDate = null;
$oneDateRowsCount = 0;
while($row = mysqli_fetch_assoc($result)) {
if ($row['Date'] == $previousDate) {
$oneDateRowsCount++;
printDateTableRow($row, ' ');
} else {
if ($previousDate !== null) {
printDateTableRow(mysqli_fetch_assoc($totalMysqliResult), 'Date total');
}
printDateTableRow($row);
$oneDateRowsCount = 1;
}
$previousDate = $row['Date'];
}
// add total for the last rows with the same date
if ($oneDateRowsCount > 1) {
printDateTableRow(mysqli_fetch_assoc($totalMysqliResult), 'Date total');
}
?>
</body>
</html>
You should refactor this code in OOP style and use PDO instead of mysqli.
So I made my first database online. I used phpmyadmin, I created the table and the user.
Now I'd like to show the table on a page of my site, as well as giving the possibility to people to edit the database from the site.
My problem is that the database does not work: it doesn't connect. I have no idea what to do.
My database is called letstenf_santi and my table passeggeri.
This is the code I'm trying to use to show the table on the site.
<?php
//establishing connection
mysql_connect('localhost', 'root', '');
//selecting a database
mysql_select_db('letstenf_santi');
$sql = 'SELECT * FROM `letstenf_santi`.`passeggeri`';
$records=mysql_query($sql);
?>
<html>
<head>
<title>mostra</title>
</head>
<body>
<table width="300" border="1" cellpadding="10" cellspacing="1">
<tr>
<th>id pass</th>
<th>nome</th>
<th>eta</th>
<th>sesso</th>
</tr>
<?php
while($pass=mysql_fetch_assoc($records)){
echo "<tr>";
echo "<td>".$pass['idpasseggero']."</td>";
echo "<td>".$pass['nome']."</td>";
echo "<td>".$pass['eta']."</td>";
echo "<td>".$pass['sesso']."</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
instead of this,
mysql_connect('localhost', 'root', '');
mysql_select_db('letstenf_santi');
you can try this,
$connection=mysql_connect('localhost', 'root', '');
$db=mysql_select_db('letstenf_santi',$connection);
try this code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "letstenf_santi";//your db name
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM tablename";//replace table name with your table name
$result = mysqli_query($conn, $sql); ?>
<html>
<head>
<title>mostra</title>
</head>
<body>
<table width="300" border="1" cellpadding="10" cellspacing="1">
<tr>
<th>id pass</th>
<th>nome</th>
<th>eta</th>
<th>sesso</th>
</tr>
<?php if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['idpasseggero']."</td>";
echo "<td>".$row['nome']."</td>";
echo "<td>".$row['eta']."</td>";
echo "<td>".$row['sesso']."</td>";
echo "</tr>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</table>
</body>
</html>
I've been trying to find an easy way for this. A search (dropdown menu) of all tables in mysql, and show their content when I click the table I want to show on the page. Instead of showing just every table on the page I thought it can be easier? Any help would be appreciated! My code so far:
<?php
$host = "localhost";
$user = "heijsdb_user";
$pass = "maus";
$db_name = "heijsdb";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
echo "borsten HFP controle";
$result = mysqli_query($connection,"SELECT * FROM borstenHFPcontrole");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table w3-table-all" border="2px">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
////////////////////////////////////////////////////////////////////////////////////////////////////////////
This is pretty much the idea, you can play from here and adapt it to your solution. Sorry I used my way, I prefer PHP template style when embedding in HTML. ;)
$host = "localhost";
$user = "heijsdb_user";
$pass = "maus";
$db_name = "heijsdb";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//check if the form was submitted
$table = filter_input(INPUT_POST, 'table', FILTER_SANITIZE_STRING);
?>
<html>
<head>
<title>showing table content on user action</title>
</head>
<body>
<div>
<form id="form-menu" method="post">
<label for="select-menu">Choose a table</label>
<select id="select-menu" name="table">
<option></option>
<?php
$result = mysqli_query($connection,"SELECT table_name FROM information_schema.tables where table_schema='test'"); // <-- the table_schema field here is your database name, change 'test' for yours
while ($row = mysqli_fetch_array($result)) : $selected = $row['table_name'] == $table ? 'selected' : ''; ?>
<option value="<?php echo $row['table_name'] ; ?>" <?php echo $selected; ?>><?php echo $row['table_name'] ; ?></option>
<?php endwhile; ?>
</select>
</form>
<hr>
<div>
<?php if (empty($table)) : ?>
<h3>Please select a table to show its content</h3>
<?php else : ?>
<h3>Content for the table `<?php echo $table; ?>`</h3>
<?php
$result = mysqli_query($connection,"SELECT * FROM `{$table}`");
$all_property = []; //declare an array for saving property
?>
<!-- showing property -->
<table class="data-table w3-table-all" border="2px">
<tr class="data-heading"> <!-- initialize table tag -->
<?php while ($property = mysqli_fetch_field($result)) : ?>
<td><?php echo $property->name; ?></td> <!-- get field name for header -->
<?php $all_property[] = $property->name; //save those to array ?>
<?php endwhile; ?>
</tr> <!-- end tr tag -->
<!-- showing all data -->
<?php while ($row = mysqli_fetch_array($result)) : ?>
<tr>
<?php foreach ($all_property as $item) : ?>
<td><?php echo $row[$item]; ?></td> <!-- get items using property value -->
<?php endforeach; ?>
</tr>
<?php endwhile; ?>
</table>
<?php endif; ?>
</div>
</div>
<script>
document.getElementById('select-menu').addEventListener('change', function() {
document.getElementById('form-menu').submit();
});
</script>
</body>
</html>
Handy links:
- Get table names using SELECT statement in MySQL
- Examples of how to do query, style, dom, ajax, event etc like jQuery with plain javascript.
Hope this helps :)
It is showing that connection has been created. But I don't know what is the problem in query. After that query I tried to echo something and it is visible there in browser.
<html>
<head>
</head>
<body>
<?php
$servername = "localhost:8888";
$username = "root";
$password = "";
$dbname = "employees";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else {
echo "Connected successfully";
}
$res = mysqli_query($conn,"select * from dept_manager");
echo"dept_manager";
while($row=mysqli_fetch_assoc($res))
{
?>
<table>
<tr>
<td><?php echo $row['emp_no'] ?></td>
<td><?php echo $row['dept_no']?></td>
<td><?php echo $row['from_date'] ?></td>
<td><?php echo $row['to_date'] ?></td>
</tr>
</table>
<?php
}
?>
</body>
</html>
$sql = "select * from dept_manager";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
// your code here
}
Try with this..
Try this in the place of while loop:
<?php
$res = mysqli_query($conn,"select * from dept_manager");
echo"dept_manager";
echo "<table>";
while($row=mysqli_fetch_assoc($res))
{
echo "<tr><td>" . $row['emp_no'] . "</td><td>" . $row['dept_no'] . "</td><td>" . $row['from_date'] . "</td><td>" . $row['to_date'] . "</td></tr>";
}
echo "</table>";
?>
You have mentioned servername:localhost:8888 just check once remove
8888 and try.
I have tried with your code in my local system,same code working fine.
Just i have entered my database name and table name,it's working fine.
So you just follow my example and test once.
COde:-
<html>
<head>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydashboard";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else{
echo "Connected successfully";
}
$res = mysqli_query($conn,"select * from content_values");
while($row=mysqli_fetch_assoc($res))
{
?>
<table>
<tr>
<td><?php echo $row['name'] ?></td>
</tr>
</table>
<?php
}
?>
</body>
</html>
Output:-
Connected successfully
Name:
Test QA AndroidSD
image sampl
GMAIL
test PDF
Nat Geo Video
I am trying to run PHP code in WAMP server using MySQL. I am creating one container,
I don't know how many containers I need. Somehow I have the count of containers generated dynamically.
I want as many containers as count. I want to apply the for loop to the below code based on count of containers.
Also I need to create CSS container classes based on count.
In the query where i am using where clause(Where Entity='ATA'), i have array of data to apply in where clause, here i have shown only one(ATA), i need the containers based on count.
<form>
<div id="container">
<div id="content">
<!-- all you need with Tablecloth is a regular, well formed table. No need for id's, class names... -->
<table cellspacing="0" cellpadding="0">
<tr >
<th class="lightcolor" style="width:60px; height:30px;"><h2>Server Name</h2></th>
<th class="lightcolor" style="width:60px; height:30px;"><h2>IP Address</h2></th>
</tr>
<?php
$user_name = "root";
$password = "";
$database = "atssautomationgnoc";
$server = "localhost";
$con = mysqli_connect($server, $user_name, $password);
$db_found = mysqli_select_db($con,$database);
$query = "SELECT Servername,IPAddress FROM t_applicationstatus Where Entity='ATA' order by FIELD(LiveStatus,'RTO','OK')";
$result=mysqli_query($con,$query);
$Names = array();
if($result == FALSE)
{
die(mysql_error());
}
$i=0;
while ($row = mysqli_fetch_array($result))
{
$rowsA[] = $row;
}
foreach($rowsA as $row)
{
$rowsA[$i]=$row['Servername'];
$rowsA[$i] = $row['IPAddress'];
echo "<tr>";
echo "<td id=health>" ;
echo $row['Servername'] ;
echo " </td>";
echo "<td id=health>" ;
echo $row['IPAddress'];
echo " </td>";
echo " </td>";
echo "</tr>";
}
?>
</table>
</div>
</form>
Say, all of the criterias you wish to specify in where clause are stored in array $entityArr.You then should add an extra loop on top of the <table> element. Try the following code.
<div id="container">
<div id="content">
<?php
$user_name = "root";
$password = "";
$database = "atssautomationgnoc";
$server = "localhost";
$con = mysqli_connect($server, $user_name, $password);
$db_found = mysqli_select_db($con,$database);
$entityArr = array("ATA", "ANOTHER", "AND_ANOTHER");
$rowsA = array(); //define rowsA
foreach ($entityArr as $entity)
{
?>
<table cellspacing="0" cellpadding="0">
<tr>
<th class="lightcolor" style="width:60px; height:30px;"><h2>Server Name</h2></th>
<th class="lightcolor" style="width:60px; height:30px;"><h2>IP Address</h2></th>
</tr>
<?php
//use $entity below in where condition
$query = "SELECT Servername,IPAddress FROM t_applicationstatus Where Entity='".$entity."' order by FIELD(LiveStatus,'RTO','OK')";
$result=mysqli_query($con,$query);
$Names = array();
if($result == FALSE)
{
die(mysql_error());
}
//clear array
unset($rowsA);
while ($row = mysqli_fetch_array($result))
{
$rowsA[] = $row;
}
foreach($rowsA as $row)
{
$rowsA[$i]=$row['Servername']; //You'd better comment this line out
$rowsA[$i] = $row['IPAddress']; //And this one
echo "<tr>";
echo "<td>" ;
echo $row['Servername'] ;
echo " </td>";
echo "<td>" ;
echo $row['IPAddress'];
echo " </td>";
echo " </td>";//This is extra, simply remove this line
echo "</tr>";
}
?>
</table>
<?php
}
?>
</div> <!-- close #content -->
</div> <!-- close #container -->
There are various ways to do this, especially without executing sql statements in the loop. Hope that helps.