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 :)
Related
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?
I am new to PHP, hoping for some help please.
I am trying to populate an HTML dropdown list with data from my SQL database.
I would like to be able to select an item from a dropdown list that would then fill an HTML table with the associated record from the database.
So far I have managed to connect to my database and retrieve all of the data from the relevant table.
Can someone please help me set this up to work through the dropdown list?
Thanks
<?php
$username = 'root';
$password = '';
$conn = new PDO( 'mysql:host=localhost; dbname=Oaktown', $username, $password );
$sql ="SELECT RoundNumber, RoundDate, HomeTeam, HomeTeamScore, AwayTeam, AwayTeamScore FROM Fixture";
$statement = $conn->prepare( $sql );
$statement->execute();
$results = $statement->fetchAll( PDO::FETCH_ASSOC );
?>
<h2>Competitions</h2>
<article>
<p id="TableHeader1">Fixture Information</p>
<P>Select Round and Game number from the dropdown list under Round Number.</P>
<br>
<br><form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<p id="TableHeader2">Round Number
<select style="width:250px"></select> <input class="button"
type="submit" name="Get" value="Get Fixture Results"></p>
<p id="TableHeader2">Results</p>
<table class="table">
<tr><td><b>Round Number:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['RoundNumber'];
}
?>
</tr>
<tr>
<td><b>Round Date:</b></td>.
<?php foreach( $results as $row ){
echo "<td>";
echo $row['RoundDate'];
}
?>
</tr>
<tr>
<td><b>Home Team:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['HomeTeam'];
}
?>
</tr>
<tr>
<td><b>Home Team Score:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['HomeTeamScore'];
}
?>
</tr>
<tr>
<td><b>Away Team:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['AwayTeam'];
}
?>
</tr>
<tr>
<td><b>Away Team Score:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['AwayTeamScore'];
}
?>
<td colspan="2><?php echo $message; ?>"></td>
</tr>
</table>
</form>
Using a similar block of code like the one you use for the tables you can do something like this:
<select>
<?php foreach( $results as $row ){
echo "<option value='" . $row['value column'] . "'>" . $row['text column'] . "</option>";
}
?>
</select>
if you don't have or need a pair of values then you can simply do this:
<select>
<?php foreach( $results as $row ){
echo "<option>" . $row['text column'] . "</option>";
}
?>
</select>
I want to know where to put the condition to display data in a table after I select the value from a dropdown list.
Both have the same id (dropdown and table).
php table
<html>
<head>
</head>
<body>
<?php
$con=mysqli_connect("localhost","root","root","company");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT employees.id,employees.jobs FROM employees WHERE employees.jobs in ("programmer","hr","qa")";
if ($result=mysqli_query($con,$sql)){
?>
<label for="y">Select the job:</label>
<select name="loads" id="loads" onchange="">
<?php while($ri = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $ri['id'];?>" > <?php echo $ri['jobs']; ?> </option>
<?php
}
}
?>
</select>
<table class="striped" border="1" align="center" id="demo">
<tr class="header">
<td align="center"><b>Name</b></td>
</tr>
<?php
$con=mysqli_connect("localhost","root","root","company");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql2="SELECT employees.id,employees.name FROM employees WHERE employees.jobs in ("programmer","hr","qa")";
if ($result=mysqli_query($con,$sql2)){
// Fetch one and one row
while ($row=mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row["name"] . " " . "</td>";
echo "</tr>";
}
}
mysqli_close($con);
?>
</table>
</body>
</html>
If you mean: you want to something happens to your table when an item get selected in dropdown list(select tag). then it is not possible through php because php codes compiled once after each load on a page and it doesnt work live!
so you have to use JQUERY and AJAX to do that.
if this is what you searching for, reply me so i can help you.
by the way you dont need to connect 2 times into database and run the same query, i just edited your code a little bit:
<html>
<head>
<title></title>
</head>
<body>
<?php $con = mysqli_connect("localhost","root","root","company");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM employees WHERE employees.jobs in ("programmer","hr","qa")";
$result = mysqli_query($con, $sql);
if ($result) { ?>
<label for="y">Select the job:</label>
<select name="loads" id="loads" onchange="">
<?php while($ri = mysqli_fetch_array($result)) { ?>
<option value="<?php echo $ri['id'];?>" > <?php echo $ri['jobs']; ?> </option>
<?php
}
}
?>
</select>
<table class="striped" border="1" align="center" id="demo">
<tr class="header">
<td align="center"><b>Name</b></td>
</tr>
<?php
// Fetch one and one row
while ($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row["name"] . " " . "</td>";
echo "</tr>";
}
mysqli_close($con);
?>
</table>
</body>
</html>
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.
I'm trying to make it so that when a button is clicked on my main page, a php script takes action and fetches the information from the SQL tables, and displays it in a HTML/CSS table.
Here's the code of my main page -
<form id="myForm" action="select.php" method="post">
<button type="submit" class="btn btn-info" >
<span class="glyphicon glyphicon-tint"></span> View
</button>
<br /> <span class="badge alert-info"> Find out what is currently in the database. </span><br />
</form>
<br />
<br />
And here's what I currently have in my select.php -
<?php
/*** mysql hostname ***/
$hostname = '192.xx.xxx.xx';
/*** mysql username ***/
$username = 'Mitchyl';
/*** mysql password ***/
$password = 'root1323';
/*** database name ***/
$dbname = 'test';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM increment";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I just don't know how to take the data from the SQL query and put it inside a HTML table.
Any suggestions would be great!
Thanks!
Try this
<?php
$hostname = '192.xx.xxx.xx';
$username = 'Mitchyl';
$password = 'root1323';
$dbname = 'test';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$sql = $dbh->prepare("SELECT * FROM increment");
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
}
catch(Exception $error) {
echo '<p>', $error->getMessage(), '</p>';
}
?>
<div id="content">
<table>
<?php while($row = $sql->fetch()) { ?>
<tr>
<td><?php echo $row['column1_name']; ?></td>
<td><?php echo $row['column2_name']; ?></td>
<td><?php echo $row['column3_name']; ?></td>
...etc...
</tr>
<?php } ?>
</table>
</div>
Let's say your sql returns an array named $data and its format is sth like $data = [['name' => 'name1'], ['name' => 'name2'], ...];.
//First declare your data array
$data = [];
// Then execute the query
$result = $mysqli->query($sql)
// Then read the results and create your $data array
while($row = $result->fetch_array())
{
$data[] = $row;
}
Now that you have your data check if it is empty or not and then use foreach to present the results.
<?php if(empty($data)): ?>
<h1>No results were found!</h1>
<?php else: ?>
<h1><?= count($data) ?> results were found!</h1>
<table class="table">
<thead>
<th>#</th>
<th>Name</th>
</thead>
<tbody>
<?php foreach ($data as $key => $value): ?>
<tr>
<td><?= ++$key ?></td>
<td><?= $value['name'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
Of course you can add any class you like to the table apart from the default one that bootstrap uses (.table).