Displaying database content - php

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);

Related

How to return an array into an HTML table using PHP

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;

Create multiple html tables with associative array in PHP

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++;
}

Display any given MySQL SELECT query as a HTML table using PHP

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.

Retrive information from list associative array in php

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

Repeating to the end of an array within a while?

I have the following code:
var_dump(explode(',',$_POST['colum_names']));
echo '<table border="1">';
$result = $con->query("" . $_POST['sql_command'] . "");
while($row = $result->fetch_array()) {
echo '<tr>';
...
echo '</tr>';
}
echo '</table>';
Inbetween the echo '<tr>' and echo '</tr>' I wish to be able to use the explode array hard to explain...
So for example it might look like:
$_POST['colum_names'] = a,b,c
=> array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" }
=> echo '<tr>'; echo $row[array[0]]; echo '</tr>';
=> echo '<tr>'; echo $row[array[1]]; echo '</tr>';
=> echo '<tr>'; echo $row[array[3]]; echo '</tr>';
If you get what I mean, I hope you can help!
$columns = explode(',',$_POST['colum_names']);
echo '<table border="1">';
$result = $con->query("" . $_POST['sql_command'] . "");
while($row = $result->fetch_array()) {
echo '<tr>';
foreach( $columns as $column ) {
echo '<td>' . $column . '</td>';
}
echo '</tr>';
}
echo '</table>';
Untested but should work

Categories