Sample Query 1 -
SELECT ID,NAME FROM USERS
Sample Query 2 -
SELECT Orders.OrderID as ID, Customers.CustomerName as Name, Orders.OrderDate as Date
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
How can I load title headings to an array in PHP?
I mean
ID,NAME in Query 1 and ID,Name,Date in Query 2
This is what I'm trying to do :
I'm creating a PHP function to make HTML table automatically from any given MySQL-Select query
This where I'm up to now
function createTable($query) {
$sql_link = Connect_MySQLi_DB();// Database Connection
$sql_link->set_charset("utf8");
$result = $sql_link->query($query);
$headings = array('ID','Name','Date');//I need this array to create automatically
echo '<table>';
echo '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
echo '<th>'.$headings[$x].'</th>';
}
echo '<tr>';
while ($row = $result->fetch_object()) {
echo '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
echo '<td>' . $row->$headings[$x] . '</td>';
}
echo '<tr>';
}
echo '</table>';
}
So I need to create that $heading array automatically.
If I can do that, this function can display any MySQL-Select query as a HTML table
If you are using mysqli then fetch_fields seems to do the job.
EDIT:
Example:
$res = $db->query('SELECT A.id,A.a,A.id + B.id AS idd FROM A natural join B');
var_dump($res->fetch_fields());
Returns information about columns A.id, A.a and about the idd column (both tables have other columns). I omitted some fields from the output in order to make it shorter.
array(3) {
[0]=>
object(stdClass)#3 (13) {
["name"]=>
string(2) "id"
["orgname"]=>
string(2) "id"
["table"]=>
string(1) "A"
["orgtable"]=>
string(1) "A"
// more fields here
}
[1]=>
object(stdClass)#4 (13) {
["name"]=>
string(1) "a"
["orgname"]=>
string(1) "a"
["table"]=>
string(1) "A"
["orgtable"]=>
string(1) "A"
// more fields here
}
[2]=>
object(stdClass)#5 (13) {
["name"]=>
string(3) "idd"
["orgname"]=>
string(0) ""
["table"]=>
string(0) ""
["orgtable"]=>
string(0) ""
// more fields here
}
}
Finally this is how I made this function to work (Thanks Hynner for your excellent suggestion),
function createTable_from_sql_select_query($query) {
$sql_link = Connect_MySQLi_DB();// Database connection
$sql_link->set_charset("utf8");
$result = $sql_link->query($query);
// Adding Missing array_column Function for Old PHP Versions (<5.5)
if (!function_exists('array_column')) {
function array_column($array, $column) {
$ret = array();
foreach ($array as $row)
$ret[] = $row[$column];
return $ret;
}
}
$headings = json_decode(json_encode($result->fetch_fields()), true);
$headings = array_column($headings, 'name');
$return = '<table>';
$return .= '<thead><tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
$return .= '<th>' . ucwords(str_replace('_', ' ', (strtolower($headings[$x])))) . '</th>';
}
$return .= '</tr></thead><tbody>';
while ($row = $result->fetch_object()) {
$return .= '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
$return .= '<td>' . $row->$headings[$x] . '</td>';
}
$return .= '</tr>';
}
$return .= '</tbody></table>';
return $return;
}
Now anyone can convert any SQL select query to a HTML table.
Related
I'm trying to display the database 'hospitaldb', collection 'doctor' content using php. I've fields email, password, fname, lname in the collection. When I try to display these fields then I get error messages as :
Notice: Undefined index: email in C:\xampp\htdocs\phpmongodb\viewdoctor.php on line 40
Notice: Undefined index: password in C:\xampp\htdocs\phpmongodb\viewdoctor.php on line 41
Notice: Undefined index: fname in C:\xampp\htdocs\phpmongodb\viewdoctor.php on line 42
Notice: Undefined index: lname in C:\xampp\htdocs\phpmongodb\viewdoctor.php on line 43
$server = "mongodb://localhost:27017/hospitaldb";
try{
$connection = new MongoDB\Client($server);
/*$hospitaldb = $connection->test;*/
$hospitaldb = $connection->hospitaldb;
}catch (MongoConnectionException $ConErrMsg)
{
echo "$ConErrMsg";
}
$data = "<table style='border:1px solid red;";
$data .= "border-collapse:collapse' border='1px'>";
$data .= "<thead>";
$data .= "<tr>";
$data .= "<th>First Name</th>";
$data .= "<th>Last Name</th>";
$data .= "<th>Email</th>";
$data .= "<th>Password</th>";
$data .= "</tr>";
$data .= "</thead>";
$data .= "<tbody>";
try{
$db = $connection->hospitaldb;
$collection = $db->doctors;
$cursor = $collection->find();
foreach ($cursor as $document)
{
$data .= "<tr>";
$data .= "<td>" . $document["email"] . "</td>";
$data .= "<td>" . $document["password"]."</td>";
$data .= "<td>" . $document["fname"]."</td>";
$data .= "<td>" . $document["lname"]."</td>";
$data .= "</tr>";
}
}catch (MongoException $mongoException)
{
echo "$mongoException";
}
Output :
object(MongoDB\Model\BSONDocument)#20 (1) {
["storage":"ArrayObject":private]=>
array(5) {
["_id"]=>
object(MongoDB\BSON\ObjectId)#16 (1) {
["oid"]=>
string(24) "5ca746b2a930602fb8000e04"
}
["email"]=>
string(16) "sanekt#gmail.com"
["password"]=>
string(6) "sanket"
["fname"]=>
string(6) "sanket"
["lname"]=>
string(6) "sanket"
}
}
object(MongoDB\Model\BSONDocument)#22 (1) {
["storage":"ArrayObject":private]=>
array(5) {
["_id"]=>
object(MongoDB\BSON\ObjectId)#21 (1) {
["oid"]=>
string(24) "5ca757fea930602fb8000e05"
}
["email"]=>
string(11) "p#gmail.com"
["password"]=>
string(4) "7888"
["fname"]=>
string(6) "piyush"
["lname"]=>
string(4) "shah"
}
}
object(MongoDB\Model\BSONDocument)#16 (1) {
["storage":"ArrayObject":private]=>
array(5) {
["_id"]=>
object(MongoDB\BSON\ObjectId)#20 (1) {
["oid"]=>
string(24) "5ca8444aa9306032cc001a32"
}
["email"]=>
string(17) "shahsir#gmail.com"
["password"]=>
string(7) "shahsir"
["fname"]=>
string(4) "Shah"
["lname"]=>
string(4) "Shah"
}
}
The question you posted is working for me :
My setup :
php 7.2 thread safe
Downloaded DLL for windows from here https://pecl.php.net/package/mongodb/1.5.3/windows. I put it in ext folder.
Composer.json
"require": {
"mongodb/mongodb": "^1.4"
}
}
Executed php code from your post
<?php
require_once __DIR__ . "/vendor/autoload.php";
$server = "mongodb://localhost:27017/hospitaldb";
try{
$connection = new MongoDB\Client($server);
/*$hospitaldb = $connection->test;*/
$hospitaldb = $connection->hospitaldb;
}catch (MongoConnectionException $ConErrMsg)
{
echo "$ConErrMsg";
}
$data = "<table style='border:1px solid red;";
$data .= "border-collapse:collapse' border='1px'>";
$data .= "<thead>";
$data .= "<tr>";
$data .= "<th>First Name</th>";
$data .= "<th>Last Name</th>";
$data .= "<th>Email</th>";
$data .= "<th>Password</th>";
$data .= "</tr>";
$data .= "</thead>";
$data .= "<tbody>";
try{
$db = $connection->hospitaldb;
$collection = $db->doctors;
$cursor = $collection->find();
foreach ($cursor as $document)
{
$data .= "<tr>";
$data .= "<td>" . $document["first_name"] . "</td>";
$data .= "<td>" . $document["last_name"]."</td>";
$data .= "</tr>";
}
}catch (MongoException $mongoException)
{
echo "$mongoException";
}
var_dump($data);
I need some help with my problem. I have administration for users where is possible create queries from actual database.
The user defines a request such as this:
["mysql_query"]=>array(3) {
[0]=>string(29) "SELECT `order`.* FROM `order`"
[1]=>string(92) "SELECT `order_product`.* FROM `order_product` WHERE `order_product`.`order_id` = {query0.id}"
[2]=>string(121) "SELECT `order_product_option`.* FROM `order_product_option` WHERE `order_product_option`.`order_product_id` = {query1.id}"
}
Then I have function for processing queries:
function mysql_structure($mysql_key, $mysql_query = null)
{
global $param, $mysql_output;
${'sql' . $mysql_key . 'db'} = (($mysql_query == null) ? $param['mysql_query'][$mysql_key] : $mysql_query);
${'query' . $mysql_key . 'db'} = get_query(${'sql' . $mysql_key . 'db'});
${'row' . $mysql_key . 'db'} = mysqli_fetch_assoc (${'query' . $mysql_key . 'db'});
${'total_rows' . $mysql_key . 'db'} = mysqli_num_rows (${'query' . $mysql_key . 'db'});
if (${'total_rows' . $mysql_key . 'db'} > 0)
{
do
{
foreach (${'row' . $mysql_key . 'db'} as $field => $value)
{
$mysql_output['query' . $mysql_key][${'row' . $mysql_key . 'db'}['id']]["{$field}"] = "{$value}";
}
if ($param['mysql_query'][($mysql_key + 1)] != null)
{
$q = get_string_between($param['mysql_query'][($mysql_key + 1)], '{', '}');
if ($q != null)
{
$qe = explode ('.', $q);
$mysql_query = str_replace ('{' . $q . '}', ${'row' . $mysql_key . 'db'}[$qe[1]], $param['mysql_query'][($mysql_key + 1)]);
}
mysql_structure(($mysql_key + 1), $mysql_query);
}
unset ($mysql_query);
}
while (${'row' . $mysql_key . 'db'} = mysqli_fetch_assoc (${'query' . $mysql_key . 'db'}));
}
}
mysql_structure(0);
$param['mysql_output'] = $mysql_output;
unset ($mysql_output);
echo '<pre>';
var_dump ($param['mysql_output']);
echo '</pre>';
Output from this function is:
array {
["query0"]=>array {
[8]=> array {
["id"]=>string(1) "8"
["cart_code"]=>string(10) "3nlc7x8ri3"
["order_code"]=>string(9) "201800010"
["user_id"]=>string(1) "1"
//...
}
[10]=> array {
["id"]=>string(2) "10"
["cart_code"]=>string(10) "awzulr7bbm"
["order_code"]=>string(9) "201800012"
["user_id"]=>string(1) "27"
//...
}
}
["query1"]=>array {
[9]=>array {
["id"]=>string(1) "9"
["product_id"]=>string(1) "5"
//...
}
[11]=>array {
["id"]=>string(1) "11"
["product_id"]=>string(1) "7"
//...
}
[12]=>array {
["id"]=>string(1) "12"
["product_id"]=>string(1) "5"
//...
}
}
["query2"]=>array {
[1]=>array {
["id"]=>string(1) "1"
["option_title"]=>string(12) "title"
//...
}
}
}
But I need create in that do-while loop multidimensional array like this:
array {
["query0"]=>array {
[8]=> array {
["id"]=>string(1) "8"
["cart_code"]=>string(10) "3nlc7x8ri3"
["order_code"]=>string(9) "201800010"
["user_id"]=>string(1) "1"
//...
["query1"]=>array {
[9]=>array {
["id"]=>string(1) "9"
["product_id"]=>string(1) "5"
//...
}
[11]=>array {
["id"]=>string(1) "11"
["product_id"]=>string(1) "7"
//...
["query2"]=>array {
[1]=>array {
["id"]=>string(1) "1"
["option_title"]=>string(12) "title"
//...
}
}
}
}
}
[10]=> array {
["id"]=>string(2) "10"
["cart_code"]=>string(10) "awzulr7bbm"
["order_code"]=>string(9) "201800012"
["user_id"]=>string(1) "27"
//...
["query1"]=>array {
[12]=>array {
["id"]=>string(1) "12"
["product_id"]=>string(1) "5"
//...
}
}
}
}
}
Thank you.
The problem are keys because this function works. Output is different, but format is what i need.
function mysql_structure($mysql_key, $mysql_query = null) {
global $param;
$sql = (($mysql_query == null) ? $param['mysql_query'][$mysql_key] : $mysql_query);
$query = get_query($sql);
$row = mysqli_fetch_assoc($query);
$total_rows = mysqli_num_rows($query);
if ($total_rows > 0) {
do {
unset ($temp);
foreach ($row as $field => $value) {
$temp["{$field}"] = "{$value}";
}
$mysql_output[] = $temp;
if ($param['mysql_query'][($mysql_key + 1)] != null) {
$q = get_string_between($param['mysql_query'][($mysql_key + 1)], '{', '}');
if ($q != null) {
$qe = explode ('.', $q);
$mysql_query = str_replace ('{' . $q . '}', $row[$qe[1]], $param['mysql_query'][($mysql_key + 1)]);
}
$mysql_output[] = mysql_structure(($mysql_key + 1), $mysql_query);
}
}
while ($row = mysqli_fetch_assoc ($query));
}
return #array_filter ($mysql_output);
}
$param['mysql_output'] = mysql_structure(0);
I can also advise with this..
I am pulling data lines from a .txt file and I am attempting to insert it into an HTML table. Right now I am stuck on outputting the array. I am able to turn the line I exploded into an array by re-exploding the line. I var_dumped the new line to ensure it is an array. I need to return a function that outputs the data into an HTML table. I do not know where to go from here. Any help is appreciated. This is as far as I got. For the sample there are about 10 books in the .txt file. Do I include HTML in the same function? or outside and how do I implement? Thank you.
PHP
function displayTable($filename)
{
$table = "\n<table border='1'>";
$table .= "<tr>";
$table .= "<th>Title</th>";
$table .= "<th>Author</th>";
$table .= "<th>ISBN</th>";
$table .= "<th>City</th>";
$table .= "</tr>\n\n";
$line_ctr = 0;
$fp = fopen($filename, 'r'); //op
ens the file for reading
if ($fp)
{
while(true)
{
$line = fgets($fp);
if (feof($fp))
{
break;
}
$line_ctr++;
//Explode into string
list($title, $author, $isbn, $city) = explode('*', $line);
$new_line = explode('*', $line);
var_dump($new_line);
}
fclose($fp ); //Close file
}
CURRENT OUTPUT SAMPLE
array(5) { [0]=> string(14) "Smart Living" [1]=> string(7) "health" [2]=> string(10) "2005-09-12" [3]=> string(13) "1-4145-5896-x" [4]=> string(2) " " }
array(5) { [0]=> string(14) "Make Money Sleeping" [1]=> string(7) "health" [2]=> string(10) "2009-01-08" [3]=> string(13) "1-4888-5896-x" [4]=> string(2) " " }
I saw your commnet. You want to sort the table. I've rewritten this function, hopefully, to help you.
You can split it to 3 step: 1.read file, 2.sort data, 3.output HTML.
function displayTable($filename)
{
// 1. read file to array
$data = array(); // Save all data read from txt file.
$fp = fopen($filename, 'r'); //opens the file for reading
if ($fp) {
while (true) {
$line = fgets($fp);
if (feof($fp)) {
break;
}
$new_line = explode('*', $line);
$data[] = $new_line; // save to data
}
fclose($fp); //Close file
}
// 2. sort data, example for sort by ISBN
if ($data) {
foreach ($data as $key => $value) {
$ISBN[$key] = $value[2]; //sort by ISBN
}
array_multisort($ISBN, SORT_ASC, $data);
}
// 3. output to HTML
$table = "\n<table border='1'>";
$table .= "<tr>";
$table .= "<th>Title</th>";
$table .= "<th>Author</th>";
$table .= "<th>ISBN</th>";
$table .= "<th>City</th>";
$table .= "</tr>\n\n";
foreach ($data as $key => $value) {
$table .= "<tr><td>" . join("</td><td>", $value) . "</td></tr>";
}
$table .= "</table>";
return $table;
}
$new_line = explode('*', $line);
$table .= "<tr><td>" . join("</td><td>", $new_line) . "</td></tr>";
}
return $table;
I have an array of arrays and accessing the data is fine, but when I try to create separate tables based on a key, which is set to the numeric month that the data pulled from the database falls under.
I have:
array(1) {
[5]=>
array(12) {
["ID"]=>
string(5) "1001"
["created_timestamp"]=>
string(26) "2015-06-11 19:10:00"
["firstname"]=>
string(4) "John"
["lastname"]=>
string(3) "Doe"
}
}
array(1) {
[5]=>
array(12) {
["ID"]=>
string(5) "1002"
["created_timestamp"]=>
string(26) "2015-06-12 19:10:00"
["firstname"]=>
string(4) "Jane"
["lastname"]=>
string(3) "Doe"
}
}
array(1) {
[6]=>
array(12) {
["ID"]=>
string(5) "1003"
["created_timestamp"]=>
string(26) "2015-07-16 19:20:00"
["firstname"]=>
string(4) "John"
["lastname"]=>
string(4) "John"
}
}
The [5] Represents the current month -1. What I want to do is create a table and headers but only once, then populate the table with first and last name.
foreach($m as $key => $value)
{
if(key($m) != $currentKey)
{
$currentKey = key($m);
}
if($key == date("n", strtotime($value['created_timestamp']))-1);
{
for($i=$currentKey; $i<=$lastkey; $i++) {
echo "<br>".count($key);
$table .= '<table id=' . date("F-Y", strtotime($m[$currentKey]['created_timestamp'])) . ' class="tblclass">
<thead><tr><th>Month</th><th>ID</th><th>Customer</th></tr></thead>';
$table .= '<tbody>';
$table .= '<tr><td>'.date("F Y", strtotime($m[$currentKey]['created_timestamp'])).'</td><td>' . $value['ID'] . '</td><td>' . $value['lastname'] . ' ' . $value['firstname'] . '</td></tr>';
$table .= '</tbody>';
$table .= '</table>';
}
}
}
Whenever I run the code it creates a table for each separate array. I want to create one table for each separate month and populate it with anything with the same key. I feel like I'm missing something though. Any help would be greatly appreciated!
A dirty solution. Since info is lacking
Here are a few assumptions:
- Array is sorted in ASC order
- There is only one item in each array [ID, Name, Timestamp]
- IF there are more items, then you can just add a loop in there
- $m is the multi-dimensional array.
NOTE: Not tested.
$currentKey = 0;
$count= 0;
$lastKey = count($m) - 1;
foreach($m as $key => $value) {
if(key($m) != $currentKey) {
$currentKey = key($m);
if($count== 0) {
echo "<br>".count($key);
$table .= '<table id=' . date("F-Y", strtotime($m[$currentKey]['created_timestamp'])) . ' class="tblclass">
<thead><tr><th>Month</th><th>ID</th><th>Customer</th></tr></thead>';
$table .= '<tbody>';
} else {
$table .= '</tbody>';
$table .= '</table>';
$table .= '<table id=' . date("F-Y", strtotime($m[$currentKey]['created_timestamp'])) . ' class="tblclass">
<thead><tr><th>Month</th><th>ID</th><th>Customer</th></tr></thead>';
$table .= '<tbody>';
}
}
if($key == date("n", strtotime($value['created_timestamp']))-1) {
$table .= '<tr><td>'.date("F Y", strtotime($value['created_timestamp'])).'</td><td>' . $value['ID'] . '</td><td>' . $value['lastname'] . ' ' . $value['firstname'] . '</td></tr>';
}
if($lastKey == $count) {
$table .= '</tbody>';
$table .= '</table>';
}
$count++;
}
Hy,
how I retrieve information from an associative array like list in php.
var_dump shows something like this:
array(2) { [1]=> string(1) "1"
[2]=> string(1) "2" }
array(2) { [1]=> string(15) "gica_craioveanu"
[2]=> string(14) "alexandra_minu" }
array(2) { [0]=> string(10) "craiovaMAX"
[1]=> string(10) "alexMinu10" }
First array containd the id's, second the user name and third the passwords.
My attempt:
foreach ($row as $i => $id,$user_name,$user_pass) {
echo "<tr>\n" .
" <td>".var_dump($id)."</td>\n".
" <td>".var_dump($user_name)."</td>\n".
" <td>".var_dump($user_pass)."</td>\n".
" </tr>\n"
}
one of php file contains the script to construct the list:
while($row = mysqli_fetch_row($result))
{
/*$id[]=$row['user_id'];
$user_name[]=$row['user_name'];
$user_pass[]=$row['user_pass'];
$i=$i+1;*/
list($id[$i],$user_name[$i],$user_pass[$i++])=$row;
}
/*for($no=0; $no<$i; $no++){
echo $row[$i]."/".$row[$i]."/";
}*/
include 'user.html.php';
}
?>
and the user.html.php
to view the rows:
<?php
// while (list($id, $user_name, $user_pass)= each($row)) {
foreach($row as $i => $id,$user_name,$user_pass){
echo " <tr>\n" .
" <td>".$id."</td>\n".
" <td>".$user_name."</td>\n".
" <td>".$user_pass."</td>\n".
" </tr>\n";
/*echo "<tr>\n" .
" <td>".var_dump($id)."</td>\n".
" <td>".var_dump($user_name)."</td>\n".
" <td>".var_dump($user_pass)."</td>\n".
" </tr>\n"
*/
/*for($no=0; $no<$i; $no++){
echo "<tr>".
"<td>".$row[$i]."</td>".
"<td>".$row[$i]."</td>".
"<td>".$row[$i]."</td>".
"</tr>";*/
}
?>
while($row = mysqli_fetch_row($result)) {
list($id[$i],$user_name[$i],$user_pass[$i++])=$row;
}
...
for($i = 1; $i < count($id) + 1; $i++) {
echo " <tr>\n" .
" <td>".$id[$i]."</td>\n".
" <td>".$user_name[$i]."</td>\n".
" <td>".$user_pass[($i - 1)]."</td>\n".
" </tr>\n";
}
$id = array("1", "2");
$user_name = array("gica_craioveanu", "alexandra_minu");
$user_pass = array("craiovaMAX", "alexMinu10");
We presume that 3 arrays are always the same size :
// You make a loop on first array
for ( $i = 0 ; $i < count($id) ; $i++ )
{
// You use index $i to access to 3 arrays.
echo 'ID: '.$id[$i].'<br />';
echo 'Name: '.$user_name[$i].'<br />';
echo 'Password: '.$user_pass[$i].'<br />';
}
for($no=1; $no<$i+1; $no++)
{
echo "<tr>".
"<td>".$id[$no]."</td>".
"<td>".$user_name[$no]."</td>".
"<td>".$user_pass[($no-1)]."</td>".
"</tr>";
}
Inspired by Typoheads