I am writing an application in which user can enter a database name and I should write all of its contents in table with using PHP.I can do it when I know the name of database with the following code.
$result = mysqli_query($con,"SELECT * FROM course");
echo "<table border='1'>
<tr>
<th>blablabla</th>
<th>blabla</th>
<th>blablabla</th>
<th>bla</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['blabla'] . "</td>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['bla'] . "</td>";
echo "</tr>";
}
echo "</table>";
In this example I can show it since I know the name of table is course and it has 4 attributes.But I want to be able to show the result regardless of the name the user entered.So if user wants to view the contents of instructors there should be two columns instead of 4.How can I accomplish this.I get the table name with html.
Table:<input type="text" name="table">
Edit:Denis's answer and GrumpyCroutons' answer are both correct.You can also ask me if you didnt understand something in their solution.
Quickly wrote this up, commented it (This way you can easily learn what's going on, you see), and tested it for you.
<form method="GET">
<input type="text" name="table">
</form>
<?php
//can be done elsewhere, I used this for testing. vv
$config = array(
'SQL-Host' => '',
'SQL-User' => '',
'SQL-Pass' => '',
'SQL-Database' => ''
);
$con = mysqli_connect($config['SQL-Host'], $config['SQL-User'], $config['SQL-Pass'], $config['SQL-Database']) or die("Error " . mysqli_error($con));
//can be done elsewhere, I used this for testing. ^^
if(!isSet($_GET['table'])) { //check if table choser form was submitted.
//In my case, do nothing, but you could display a message saying something like no db chosen etc.
} else {
$table = mysqli_real_escape_string($con, $_GET['table']); //escape it because it's an input, helps prevent sqlinjection.
$sql = "SELECT * FROM " . $table; // SELECT * returns a list of ALL column data
$sql2 = "SHOW COLUMNS FROM " . $table; // SHOW COLUMNS FROM returns a list of columns
$result = mysqli_query($con, $sql);
$Headers = mysqli_query($con, $sql2);
//you could do more checks here to see if anything was returned, and display an error if not or whatever.
echo "<table border='1'>";
echo "<tr>"; //all in one row
$headersList = array(); //create an empty array
while($row = mysqli_fetch_array($Headers)) { //loop through table columns
echo "<td>" . $row['Field'] . "</td>"; // list columns in TD's or TH's.
array_push($headersList, $row['Field']); //Fill array with fields
} //$row = mysqli_fetch_array($Headers)
echo "</tr>";
$amt = count($headersList); // How many headers are there?
while($row = mysqli_fetch_array($result)) {
echo "<tr>"; //each row gets its own tr
for($x = 1; $x <= $amt; $x++) { //nested for loop, based on the $amt variable above, so you don't leave any columns out - should have been <= and not <, my bad
echo "<td>" . $row[$headersList[$x]] . "</td>"; //Fill td's or th's with column data
} //$x = 1; $x < $amt; $x++
echo "</tr>";
} //$row = mysqli_fetch_array($result)
echo "</table>";
}
?>
$tablename = $_POST['table'];
$result = mysqli_query($con,"SELECT * FROM $tablename");
$first = true;
while($row = mysqli_fetch_assoc($result))
{
if ($first)
{
$columns = array_keys($row);
echo "<table border='1'>
<tr>";
foreach ($columns as $c)
{
echo "<th>$c</th>";
}
echo "</tr>";
$first = false;
}
echo "<tr>";
foreach ($row as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
<?php
$table_name = do_not_inject($_REQUEST['table_name']);
$result = mysqli_query($con,'SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='. $table_name);
?>
<table>
<?php
$columns = array();
while ($row = mysql_fetch_assoc($result)){
$columns[]=$row['COLUMN_NAME'];
?>
<tr><th><?php echo $row['COLUMN_NAME']; ?></th></tr>
<?php
}
$result = mysqli_query($con,'SELECT * FROM course'. $table_name);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
foreach ($columns as $column){
?>
<td><?php echo $row[$column]; ?></td>
<?php
}
echo '</tr>';
}
?>
</table>
Related
I want to read out data from an sql-database an show them in a table. This works well. Now, I would like to show only those columns with at least one value in it and not the empty ones (containing NULL, 0, empty string). This works with the following example:
enter code here
<TABLE width="500" border="1" cellpadding="1" cellspacing="1">
<?php
$query = mysql_query("SELECT * FROM guestbook", $db);
$results = array();
while($line = mysql_fetch_assoc($query)){
$results[] = $line;
$Name = array_column($results, 'Name');
$Home = array_column($results, 'Home');
$Date = array_column($results, 'Date');
$Emptycolumn = array_column($results, 'Emptycolumn');
$Comment = array_column($results, 'Comment');
$City = array_column($results, 'City');
}
echo "<TR>";
if(array_filter($Name)) {echo "<TH>Name</TH>";}
if(array_filter($Home)){echo "<TH>Home</TH>";}
if(array_filter($Date)){echo "<TH>Date</TH>";}
if(array_filter($Emptycolumn)){echo "<TH>Emptycolumn</TH>";}
if(array_filter($Comment)){echo "<TH>Comment</TH>";}
if(array_filter($City)){echo "<TH>City</TH>";}
echo "</TR>";
$query = mysql_query("SELECT * FROM guestbook", $db);
while($line = mysql_fetch_assoc($query)){
echo "<TR>";
if(array_filter($Name)) {echo "<TD>".$line['Name']."</TD>";}
if(array_filter($Home)) {echo "<TD>".$line['Home']."</TD>";}
if(array_filter($Date)) {echo "<TD>".$line['Date']."</TD>";}
if(array_filter($Emptycolumn)) {echo "<TD>".$line['Emptycolumn']."</TD>";}
if(array_filter($Comment)) {echo "<TD>".$line['Comment']."</TD>";}
if(array_filter($City)) {echo "<TD>".$line['City']."</TD>";}
echo "</TR>";
}
?>
</TABLE>
Since the column-names of my table are highly variable (depending on the query), the table is generated by looping through the result-array, first the column-names, then the values in the rows:
enter code here
$sql = "SELECT DISTINCT $selection FROM $tabelle WHERE
$whereclause"; //will be changed to PDO
$result = mysqli_query($db, $sql) or die("<b>No result</b>"); //Running
the query and storing it in result
$numrows = mysqli_num_rows($result); // gets number of rows in result
table
$numcols = mysqli_num_fields($result); // gets number of columns in
result table
$field = mysqli_fetch_fields($result); // gets the column names from the
result table
if ($numrows > 0) {
echo "<table id='myTable' >";
echo "<thead>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
$key = array_search($field[$x]->name, $custom_column_arr);
if($key !== false){
echo "<th>" . $key . "</th>";
}else{
echo "<th>" . $field[$x]->name . "</th>";
}
}
echo "</tr></thead>";
echo "<tbody>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) { // goes around until there are no
columns left
echo "<td>" . $row[$field[$k]->name] . "</td>"; //Prints the data
}
echo "</tr>";
$nr = $nr + 1;
} // End of while-loop
echo "</tbody></table>";
}
}
mysqli_close($db);
Now, I tried to integrate the array_column() and array_filter()-blocks of the example above into the loops, but unfortunately, it didn´t work. I´m sure, this is easy for a professional and I would be very grateful, if someone could help me with this problem!
Thank you very much in advance!!
I am trying to get the column names and data from a table using mysqli and php. Any help is appreciated.
I know how to do this in java by more or less this code:
String [] header= new String[numberOfColumns-1];
//Code to get column names in header array
String table = "<table><tr>"
for(int i=0;i<numberOfColumns-1;i++){
table= table + "<td>" + header[i] + </td>;
}
table = table + </tr>;
while(result.next()!=null){
table = table + <tr>
for (int j = 0 ; j < numberOfColumns-1 ; j++){
table = table + <td> + result.getString[j] + </td>
}
table = table + </tr>
}
But i have no idea how to do it in php. Each table is different but what i have to far for the one table:
include("config.php");
session_start();
$sql = ($_POST['q']);
$result = mysqli_query($db,$sql);
echo "<tr>";
echo "<td>First Name</td>";
echo "<td>Last Name</td>";
echo "<td>Date of Birth</td>";
echo "<td>Contact Details</td>";
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
echo "<td>" . $rowitem['fname'] . "</td>";
echo "<td>" . $rowitem['lname'] . "</td>";
echo "<td>" . $rowitem['dob'] . "</td>";
echo "<td>" . $rowitem['contact'] . "</td>";*/
echo "</tr>";
}
echo "</table>"; //end table tag
EDIT: Is the implementation of the fetch_fields correct?
include("config.php");
session_start();
$sql = ($_POST['q']);
$result = mysqli_query($db,$sql);
$finfo = mysqli_fetch_fields($result);
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>" . $val->name . "</td>"
}
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
for($x =0; $x < count($finfo);$x++){
echo "<td>" . $rowitem[$x] . "/td";
}
echo "</tr>";
}
echo "</table>";
EDIT 2: Database Connection.php
<<?php
include("config.php");
session_start();
$sql = ($_GET['q']);
$result = mysqli_query($db,$sql);
echo "<table border='1' class='table_info'>";
$finfo = mysqli_fetch_fields($result);
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>" . $val->name . "</td>";
}
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
foreach ($row as $value) { (line 18)
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>"; //end table tag
?>
Error:
Notice: Undefined variable: row in databaseConnection.php on line 18
Warning: Invalid argument supplied for foreach() in databaseConnection.php on line 18
You can call mysqli_fetch_fields on the $result object, and retrieve the name property for each object in the returned array. See documentation for examples.
There are a couple ways to do this:
Use array_keys() to grab the names of the keys from an associative array:
$rowitem = mysqli_fetch_array($result, MYSQLI_ASSOC);
$header = array_keys($rowitem);
Use mysqli_fetch_fields() to grab the field objects, and parse out the names into an array using array_map():
// Helper function to use in array_map
// (For PHP < 5.3. If >= 5.3.0, use the second version)
function getFieldName($field) { return $field->name; }
// For PHP < 5.3:
$header = array_map("getFieldName", mysqli_fetch_fields($result));
// For PHP >= 5.3.0:
$header = array_map(function($o) { return $o->name; }, mysqli_fetch_fields($result));
As mentioned you can use $result->fetch_fields() to get the field information from the result and this includes the name of each field.
For what you're trying to acheive this code should work for pretty much any table/query:
<?php
/* Connect to mysql */
$mysqli = new mysqli("localhost", "username", "password", "database");
/* Check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Your query */
$query = "SELECT * from table";
if ($result = $mysqli->query($query)) {
/* Output HTML table */
echo "<table border='1'>";
/* Get field information for all returned columns */
$finfo = $result->fetch_fields();
/* Output each column name in first table row */
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>".$val->name."</td>";
}
echo "</tr>";
/* Fetch the result and output each row into a table row */
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
$result->free();
echo "</table>";
}
$mysqli->close();
(Obviously you should never query a database from a $_POST variable without some serious sanitisation of the input, but I'll assume that was just for your convenience.)
You can Echo in a table..
$result = mysqli_query($db,$sql)
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysqli_num_fields($result);
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysqli_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysqli_free_result($result);`
I need to output a table based on two other tables as shown below:
case: there are two table "tbl_schedule" and "tbl_report"
this is my script:
$sql = mysql_query("SELECT*, count(*) as schedule_date FROM mst_schedule WHERE schedule_date LIKE '%$date' GROUP BY schedule_account") or die (mysql_error());
while ($data = mysql_fetch_array($sql)) {
$account = schAccount($data['schedule_account']);
$sql2 = mysql_query("SELECT * FROM trn_reportsch WHERE schedule_id='$data[schedule_id]' GROUP BY schedule_id");
echo "<tr>";
echo "<td>".ucfirst($account['admin_fullname'])."</td>";
while ($data2 = mysql_fetch_array($sql2)) {
echo "<td>".$data2['rating']."</td>";
}
echo "<td>".$data['schedule_date']."</td>";
echo "</tr>";
}
So far I don't get the desired output. How should I change the script?
Your code is almost correct.
Add following lines:
$sql = mysql_query("SELECT*, count(*) as schedule_date FROM mst_schedule WHERE schedule_date LIKE '%$date' GROUP BY schedule_account") or die(mysql_error());
while ($data = mysql_fetch_array($sql)) {
$account = schAccount($data['schedule_account']);
$sql2 = mysql_query("SELECT * FROM trn_reportsch WHERE schedule_id='$data[schedule_id]' GROUP BY schedule_id");
echo "<tr>";
echo "<td>" . ucfirst($account['admin_fullname']) . "</td>";
$bad = $good = $vGood = 0; // <-- ADD THIS LINE
while ($data2 = mysql_fetch_array($sql2)) {
if($data2['rating'] <=2){ // BAD
$bad++;
} else if($data2['rating'] <= 3){ // GOOD
$good++;
} else if($data2['rating'] > 3){ // VERY GOOD
$vGood++;
}
}
echo "<td>" . $bad . "</td>"; // Display the final value for bad
echo "<td>" . $good . "</td>"; // Display the final value for good
echo "<td>" . $vGood . "</td>"; // Display the final value for very good
echo "<td>" . $data['schedule_date'] . "</td>";
echo "</tr>";
}
I am trying to create a dynamically made table that will display multiple drop down lists within each row with previously selected values that are stored within a DB.
Currently I am stuck on just displaying the proper values within each <td>.
//$query..
$data = mysqli_query($dbc, $query);
echo"<table>
<tr>
<th>Component</th>
<th>Component Type</th>
<th>Component Thickness</th>
</tr>";
while ($row = mysqli_fetch_array($data)) { //while I have rows..
//add column values to an array
$facSecComponentID[] = $row['facility_section_components_id'];
$facSecComponent[] = $row['roof_component_id'];
$facSecComponentType[] = $row['roof_component_type_id'];
$facSecComponentThickness[] = $row['component_thickness'];
//try to loop through each index of each row and get the DB value..
//eventually use this value to assign a selected index within the drop down list
foreach ($row as $componentIndex => $selectedComponent) {
echo "<tr>";
echo "<td>" . $facSecComponent[$selectedComponent] . "</td>";
echo "<td>" . $facSecComponentType[$selectedComponent] . "</td>";
echo "<td>" . $facSecComponentThickness[$selectedComponent] . "</td>";
echo "</tr>";
}
}
echo "</table>";
I can't get the values I need here to display properly, I have also tried to do something like: "<td>" . $componentIndex[$selectedComponent] . "</td>"; which didn't help.
I keep getting undefined index errors or all fields being a single value.
Let me know if anything is unclear or needs further explanation and I will try to make my question more clear.
Any help would be great,
Thanks
Try:
$facSecComponentID = array();
$facSecComponent = array();
$facSecComponentType = array();
$facSecComponentThickness = array();
while ($row = mysqli_fetch_array($data)) {
$facSecComponentID[] = $row['facility_section_components_id'];
$facSecComponent[] = $row['roof_component_id'];
$facSecComponentType[] = $row['roof_component_type_id'];
$facSecComponentThickness[] = $row['component_thickness'];
}
$numItems = mysqli_num_rows($result);
for($i=0;$i<$numItems;$i++){
echo "<tr>";
echo "<td>{$facSecComponent[$i]}</td>";
echo "<td>{$facSecComponentType[$i]}</td>";
echo "<td>{$facSecComponentThickness[$i]}</td>";
echo "</tr>";
}
It's better if you concatenate a string like
$this->Table ="<table>";
while($MyRow = mysqli_fetch_array($fect)){
$this->Table .="<tr><td>".$MyRow['data']."</td></tr>";
}
$this->Table .="</table>";
return $this->Table ;
I have created an sql database(with phpmyadmin) filled with measurements from which I want to call data between two dates( the user selects the DATE by entering in the HTML forms the "FROM" and "TO" date) and display them in a table.
Additionally I have put, under my html forms, some checkboxes and by checking them you can restrict the amount of data displayed.
Each checkbox represent a column of my database; so along with the date and hour column, anything that is checked is displayed(if none is checked then everything is displayed).
So far I managed to write a php script that connects to the database, display everything when none of my checkboxes is checked and also managed to put in order one of my checkboxes.
Problem: The data that I call for are been displayed twice.
Question: I want to have four checkboxes.
Do I need to write an sql query for every possible combination or there is an easier way?
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_Database_Test = "localhost";
$database_Database_Test = "database_test";
$table_name = "solar_irradiance";
$username_Database_Test = "root";
$password_Database_Test = "";
$Database_Test = mysql_pconnect($hostname_Database_Test, $username_Database_Test, $password_Database_Test) or trigger_error(mysql_error(),E_USER_ERROR);
//HTML forms -> variables
$fromdate = $_POST['fyear'];
$todate = $_POST['toyear'];
//DNI CHECKBOX + ALL
$dna="SELECT DATE, Local_Time_Decimal, DNI FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$tmp ="SELECT * FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$entry=$_POST['dni'];
if (empty($entry))
{
$result = mysql_query($tmp);
echo
"<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>
<th>Solar_time_decimal</th>
<th>GHI</th>
<th>DiffuseHI</th>
<th>zenith_angle</th>
<th>DNI</th>
";
while( $row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal'] . "</td>";
echo "<td>" . $row['Solar_Time_Decimal'] . "</td>";
echo "<td>" . $row['GHI'] . "</td>";
echo "<td>" . $row['DiffuseHI'] . "</td>";
echo "<td>" . $row['Zenith_Angle'] . "</td>";
echo "<td>" . $row['DNI'] . "</td>";
echo "</tr>";
}
echo '</table>';}
else
{
$result= mysql_query($dna);
echo
"<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>
<th>DNI</th>
";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal']."</td>";
echo "<td>" . $row['DNI'] . "</td>";
echo "</tr>";
}
echo '</table>';
}
if($result){
echo "Successful";
}
else{
echo "Enter correct dates";
}
?>
<?php
mysql_close();
?>
Try to create your checkbox like below:
Solar_Time_Decimal<checkbox name='columns[]' value='1'>
GHI<checkbox name='columns[]' value='2'>
DiffuseHI<checkbox name='columns[]' value='3'>
Zenith_Angle<checkbox name='columns[]' value='4'>
DNI<checkbox name='columns[]' value='5'>
And try to hange your PHP code to this:
<?php
//HTML forms -> variables
$fromdate = isset($_POST['fyear']) ? $_POST['fyear'] : data("d/m/Y");
$todate = isset($_POST['toyear']) ? $_POST['toyear'] : data("d/m/Y");
$all = false;
$column_names = array('1' => 'Solar_Time_Decimal', '2'=>'GHI', '3'=>'DiffuseHI', '4'=>'Zenith_Angle','5'=>'DNI');
$column_entries = isset($_POST['columns']) ? $_POST['columns'] : array();
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
if (empty($sql_columns)) {
$all = true;
$sql_columns[] = "*";
} else {
$sql_columns[] = "DATE,Local_Time_Decimal";
}
//DNI CHECKBOX + ALL
$tmp ="SELECT ".implode(",", $sql_columns)." FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$result = mysql_query($tmp);
echo "<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
while( $row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal'] . "</td>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
echo '</table>';
if($result){
echo "Successful";
}
else{
echo "Enter correct dates";
}
?>
<?php
mysql_close();?>
This solution consider your particular table columns but if your wish a generic solution you can try to use this SQL too:
$sql_names = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$database_Database_Test' AND TABLE_NAME = '$table_name'";
and use the result to construct the $column_names array.
Solution for your problem : Change the mysql_fetch_assoc with mysql_fetch_array
If you have the same problem try to print your result with print_r
Answer : Use the bit datatype in mysql for store and read your checkboxes.
When you're receiving thr value from the database then you can use
in the parameter checked you can use the php code as exist :
$value = ...get the value from db ( 1 or 0 )
echo '<input type="checkbox" name="thename" value="thevalue" '.($value==1?'checked=checked'.'').'/>';