Building an edit/update database form - adding column - php

I am working on an update database record form. The data is fetched from db table and populated into an html table on the webpage. I am stuck now how to add another column (5th) in the table that will contains 'edit' href link for updating database script.
Like:
|Col1|Col2|Col3|Col4|Edit|
| -- | -- | -- | -- |href|
I know this is very basic question, but so far I am not able to solve it.
It will be very helpful if someone can help me to work it.
Here is my code:
<div id="update" class="col mb-4">
<?php
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:150px;border:1px solid grey;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
echo "<table class='table-bordered'>";
echo "<thead class='table-dark'>";
echo "<tr><th>Col1</th><th>Col2<th>Col3</th><th>xCol4</th></tr>";
echo "</thead>";
echo "<tbody>";
try {
$stmt = $conn->prepare("SELECT Col1, Col2, Col3, Col14 FROM table");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// $conn = null;
echo "</tbody>";
echo "</table>";
?>
</div>

Your code is very overcomplicated, which is what's making it hard to modify.
It seems like you just want to do a simple table with data from a database. You could basically just do:
<div id="update" class="col mb-4">
<table class='table-bordered'>
<thead class='table-dark'>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<?php
try {
$stmt = $conn->prepare("SELECT Col1, Col2, Col3, Col14 FROM table");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $row) {
?>
<tr>
<td style='width:150px;border:1px solid grey;'><?= $row['Col1'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col2'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col3'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col4'] ?></td>
<td style='width:150px;border:1px solid grey;'>Edit</td>
</tr>
<?php
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</tbody>
</table>
</div>
I would also recommending moving the database query away from the view into a class or something. Then the view would be much cleaner (no try/catch etc). Then all the PHP in the view would be something like:
<?php foreach ($myClass->getTheData() as $row) : ?>
<tr>
<td style='width:150px;border:1px solid grey;'><?= $row['Col1'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col2'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col3'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col4'] ?></td>
<td style='width:150px;border:1px solid grey;'>Edit</td>
</tr>
<?php endforeach ?>
Now it would be much easier to change the HTML.

Related

How do I display my database in table form using PHP html?

How do I display my database in table form. Here my code:
<?php
$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"order");
$res=mysqli_query($link,"select * from ordersum");
while($row=mysqli_fetch_array($res))
{
echo $row["name"]." ".$row["email"]." ".$row["content"]." ".$row["date"]." ".$row["amount"];
echo "<br>";
}
?>
Try this, hope can help you.
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Content</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php
$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"order");
$res=mysqli_query($link,"select * from ordersum");
while($row=mysqli_fetch_array($res)){
echo "<tr>
<td>".$row["name"]."</td>
<td>".$row["email"]."</td>
<td>".$row["content"]."</td>
<td>".$row["date"]."</td>
<td>".$row["amount"]."</td>
</tr>";
}
?>
</tbody>
</table>
Your code should look like this:
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Content</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<?php
// your connection code here
while($row=mysqli_fetch_array($res)) { ?>
<td><?php echo $row["name"];?></td>
<td><?php echo $row["email"];?></td>
<td><?php echo $row["content"];?></td>
<td><?php echo $row["date"];?></td>
<td><?php echo $row["amount"];?></td>
<?php } ?>
</tr>
</tbody>
</table>
Try to NOT echo HTML tags, this is not a good practice, instead, close php, render html, echo your PHP values and make sure to close your loop (while, for, foreach) at the end of it.
I try use this code.
<html>
<body>
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Name</th><th>Email</th><th>Content</th><th>Date</th><th>Amount</th></tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width: 150px; border: 1px solid black;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "order";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM ordersum");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
</body>
</html>
<?php
$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"order");
$res=mysqli_query($link,"select * from ordersum");
?>

save values from editable table using php

Hi I have a table generated from php, it is editable, I want to save edited values to database. I have no Idea how can I do this as there are many rows(dynamic) on a page.
Here is a screen-shot:-
Please suggest
Edit:-
My code is
echo "<table border='1'>
<tr>
<th>Sl Number</th>
<th>Product Id</th>
<th>Product Name</th>
<th>Product Catagory</th>
<th>Retal Price</th>
<th>Max Price</th>
<th>Min Price</th>
<th>Initial Stock</th>
<th>Quantity Sold</th>
<th>Current Stock</th>
<th>Last Order</th>
<th>Edit/Update</th>
</tr>";
while($row = $result->fetch_assoc())
{
echo "<tr contenteditable>";
echo "<td>" . $row["Row Number"]. "</td>";
echo "<td>" . $row["Product Id"]. "</td>";
echo "<td>" . $row["Product Name"]. "</td>";
echo "<td>" . $row["Product Catagory"]. "</td>";
echo "<td>" . $row["Retal Price"]. "</td>";
echo "<td>" . $row["Max Price"]. "</td>";
echo "<td>" . $row["Min Price"]."</td>";
echo "<td>" . $row["Initial Stock"]."</td>";
echo "<td>" . $row["Quantity Sold"]. "</td>";
echo "<td>" . $row["Current Stock"]."</td>";
echo "<td>" . $row["Last Order"]."</td>";
echo "<td contenteditable = 'false'><button href = '#'>Update</a></td>";
echo "</tr>";
}
Let me give you with the best way
First your database tables have spaces: correct that e.g.
from $row["Initial Stock"] to $row["Initial_Stock"]
Then i will propose you use ajax instead of wasting time clicking buttons
The HTML Page
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script>
$(function(){
$("#loading").hide();
//acknowledgement message
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var field_userid = $(this).attr("id") ;
var value = $(this).text() ;
$.post('update.php' , field_userid + "=" + value, function(data){
if(data != '')
{
message_status.show();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.hide()},1000);
}
});
});
});
</script>
<style>
table.zebra-style {
font-family:"Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
text-align:left;
border:1px solid #ccc;
margin-bottom:25px;
width:100%
}
table.zebra-style th {
color: #444;
font-size: 13px;
font-weight: normal;
padding: 5px 4px;
}
table.zebra-style td {
color: #777;
padding: 4px;
font-size:13px;
}
table.zebra-style tr.odd {
background:#f2f2f2;
}
#status { padding:10px; position:fixed; top:10px; border-radius:5px; z-index:10000000; background:#88C4FF; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
#loading { padding:10px; position:absolute; top:10px; border-radius:5px; z-index:10000000; background:#F99; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
</style>
<div id="status"> </div>
<div id="loading"></div>
<table id="tableID" border="0" class="sortable table zebra-style">
<thead>
<tr>
<th>Sl Number</th>
<th>Product Id</th>
<th>Product Name</th>
<th>Product Catagory</th>
<th>Retal Price</th>
<th>Max Price</th>
<th>Min Price</th>
<th>Initial Stock</th>
<th>Quantity Sold</th>
<th>Current Stock</th>
<th>Last Order</th>
<th>Edit/Update</th>
</tr>
</thead>
<tbody class="list">
<?php do { ?>
<tr>
<td contenteditable="true" id="Row_Number:<?php echo $row["Row_Number"]; ?>"><?php echo $row["Row_Number"]; ?></td>
<td contenteditable="true" id="Product_Id:<?php echo $row["Product_Id"]; ?>"><?php echo $row["Product_Id"]; ?></td>
<td contenteditable="true" id="Product_Name:<?php echo $row["Product_Name"]; ?>"><?php echo $row["Product_Name"]; ?></td>
<td contenteditable="true" id="Product_Catagory:<?php echo $row["Product Id"]; ?>"><?php echo $row["Product_Catagory"]; ?></td>
<td contenteditable="true" id="Retal_Price:<?php echo $row["Retal_Price"]; ?>"><?php echo $row["Retal_Price"]; ?></td>
<td contenteditable="true" id="Max_Price:<?php echo $row["Max_Price"]; ?>"><?php echo $row["Max_Price"]; ?></td>
<td contenteditable="true" id="Min_Price:<?php echo $row["Min_Price"]; ?>"><?php echo $row["Min_Price"]; ?></td>
<td contenteditable="true" id="Initial_Stock:<?php echo $row["Initial_Stock"]; ?>"><?php echo $row["Initial_Stock"]; ?></td>
<td contenteditable="true" id="Quantity_Sold:<?php echo $row["Quantity_Sold"]; ?>"><?php echo $row["Quantity_Sold"]; ?></td>
<td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo $row["Last_Order"]; ?></td>
<td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo $row["Last_Order"]; ?></td>
<td contenteditable = 'false'></td>";
</tr>
<?php } while($row = $result->fetch_assoc()) ?>
</tbody>
</table>
And the update php page
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8',
'username',
'password',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
?>
<?php
if(!empty($_POST))
{
//database settings
foreach($_POST as $field_name => $val)
{
//clean post values
$field_id = strip_tags(trim($field_name));
//from the fieldname:user_id we need to get user_id
$split_data = explode(':', $field_id);
$product_id = $split_data[1];
$field_name = $split_data[0];
if(!empty($product_id) && !empty($field_name) && !empty($val))
{
$affected_rows = $db->exec("UPDATE yourtable SET $field_name = '$val' WHERE product_ID = $product_id");
echo $affected_rows;
echo "Updated";
} else {
echo "Invalid Requests";
}
}
}
else {
echo "Invalid Requests";
}
?>
To save the whole table, you could leave the row-level update buttons out, and have a single save button:
<button id="save">Save</button>
<div id="msg"></div>
The msg area is to display feed-back from the server when the save-operation is performed.
Then you would add this JavaScript to handle the click of the save button:
$('#save').click(function() {
var data = [];
$('td').each(function() {
var row = this.parentElement.rowIndex - 1; // excluding heading
while (row >= data.length) {
data.push([]);
}
data[row].push($(this).text());
});
$.post('savetable.php', {table: data}, function (msg) {
$('#msg').text(msg);
});
});
This will transform the HTML table contents, without header row, to a JavaScript matrix, which then is sent to savetable.php for processing.
In PHP you would then use $_POST['table'] to access that array. When you implement this, first debug, and do a var_dump($_POST['table']) to make sure the data was transferred correctly, and it has the array structure you expect.
Then loop over that array to insert the rows into your database. You can use mysqli or PDO for this.
The PHP script savetable.php should only echo one message: a confirmation ("the table was saved successfully") or an error message ("a problem occurred. Your data was not saved.").
It should not reproduce the HTML of the table, since that is already displayed in the browser. Whatever PHP prints will be used by the JavaScript code to be displayed below the save button.
Here is how savetable.php could look like. But please debug carefully, I did not test this code. And before it works, you first need to set up your database model of course:
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4',
'username', 'password');
// Configure that all database errors result in an exception:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// Make a transaction: this allows to rollback any of the changes
// if anything goes wrong before the end of it.
$db->beginTransaction();
// First delete all rows.
$db->exec("DELETE FROM mytable");
// Prepare a statement that will be executed for each row.
// Needs to be extended for all columns:
$stmt = $db->prepare("INSERT INTO mytable (sl_num, product_id, product_name)
VALUES (?, ?, ?)");
foreach ($_POST('table'] as $row) {
$stmt->execute($row); // the columns are passed to the prepared statement.
}
// All went well: commit the changes.
$db->commit();
echo "Table saved successfully";
} catch(PDOException $e) {
// Something went wrong: roll back any changes made
$db->rollback();
echo "An error occurred: " . $e->getMessage();
}
What you can do is ajax call to a php with the id of the row you want to save and the new data. Then use PDO to connect to the database and update the information. After that is done, use javascript to edit the table itself.
So what you need to do is look up how to use ajax calls and use PDO. I suggest when you echo the table itself
<button href = '#' onclick="updateRow('. $row['Row Number'] .')">Update</a></td> where Row Number is the ID in the database and updateRow() is the javascript function you will create to get the new information and send it via ajax. Don't use mysql_*, because it is not supported in php 7 and it will die soon. Look up PDO instead.

Select an sql field from html field and show it in another page

I have displayed sql table in html table, made a hyperlink near all fields, when i click it the whole field details should be shows in other page(ie; i show only 2 fields of sql in the table and want to show rest in another page).
admin.php
<?php
$con= mysql_connect("localhost","root","");
mysql_select_db("main",$con);
echo"<form action=\"post\" class=\"form-horizontal\" role=\"form\">";
echo "<table width='700' height='150' onclick='myFun(event)'>";
echo" <tr>
<td width='100' align='center'></td>
<td width='100' align='center'><b><u>NAME</u></b></td>
<td width='100' align='left'><b><u>E-MAIL</u></b></td>
</tr>
";
$result=mysql_query("select NAME,EMAIL from admin order by AID");
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo"<td width='100' align='center'><a href='viewadmin.php?name=".$row['NAME']."'>Select</a></td>";
echo"<td width='100' align='center'>".$row['NAME']."</td>";
echo"<td width='100' align='left'>".$row['EMAIL']."</td>";
echo"</tr>";
}
echo"</table>";
echo"</form> ";
?>
viewadmin.php
<?php
$name = $_GET['name'];
$result=mysql_query("SELECT NAME,DOB,MOB,EMAIL, FROM admin WHERE NAME = $name");
if (false === $result) {
echo mysql_error();
}
else {
$row=mysql_fetch_row($result);
}
echo" <form class=\"form-horizontal\" role=\"form\">
<table width='400'>
<tr>
<td align='left'>Name</td>
<td align='left'>".$row['NAME']."</td>
</tr>
<tr>
<td align='left'>E-mail</td>
<td align='left'>".$row['EMAIL']."</td>
</tr>
<tr>
<td align='left'>D.O.B</td>
<td align='left'>".$row['DOB']."</td>
</tr>
<tr>
<td align='left'>Mobile</td>
<td align='left'>".$row['MOBILE']."</td>
</tr>
<tr>
<td align='left'>Photo</td>
<td ><img src='uploads/grumpy.jpg' height='200' width='200'></td>
</tr>
</table>";
echo"</form> ";
?>
do something like this:
admin.php
$result=mysql_query("select NAME,EMAIL from admin order by AID");
while($row=mysql_fetch_array($result)) {
echo "<tr>";
echo"<td width='100' align='center'><a href='viewadmin.php?name=".$row['NAME']."'>Select</a></td>";
echo"<td width='100' align='center'>".$row['NAME']."</td>";
echo"<td width='100' align='left'>".$row['EMAIL']."</td>";
echo"</tr>";
}
echo"</table>";
and in viewadmin.php
$name = $_GET['name'];
$result=mysql_query("SELECT * FROM admin WHERE name = $name");
$row=mysql_fetch_row($result);
echo " <form class=\"form-horizontal\" role=\"form\">
<table width='400'>
<tr>
<td align='left'>".$row['NAME']."</td>
<td align='left'></td>
</tr>
<tr>
<td align='left'>".$row['EMAIL']."</td>
<td align='left'>...";
first rename the html page by php page, then you can pass the primary key or any key of the row from first page to admin page with the help of GET.
for eg:
first.php
<?php
$result=mysql_query("select ID,NAME,EMAIL from admin order by AID"); while($row=mysql_fetch_array($result)){
?><a hre='admin.php?id="$id=<?php $row[0] ?>"'></a>
<?php
}
?>
and in the admin.php page
you can access the value like
echo $_GET['id'];
stop using MySQL and use MySQLi, this code should work
<?php
$db_connect = mysqli_connect('localhost', 'root', 'pass', 'database');
if (mysqli_connect_errno($db_connect)) {
die('Some error occurred during connection to the database');
}
$name = mysqli_real_escape_string($db_connect,$_REQUEST['name']);
if($stmt = mysqli_prepare($db_connect, 'SELECT * FROM admin WHERE name = ?')){
mysqli_stmt_bind_param($stmt, 's', $name);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) !== 0){
$row = mysqli_fetch_assoc($result);
echo "<form class=\"form-horizontal\" role=\"form\">
<table width='400'>
<tr>
<td align='left'>".$row['NAME']."</td>
<td align='left'></td>
</tr>
<tr>
<td align='left'>".$row['EMAIL']."</td>
<td align='left'>..."
}
else{
echo 'not found';
}
}
else{
trigger_error('error:' . mysqli_errno($db_connect) . mysqli_error($db_connect));
}
?>

Show Additional Form Data when Result is Isolated

I have a form that displays the results from a survey into a webpage. At the moment, when a user clicks on the 'View Here' it takes them to the individual entry for that ID. When it is clicked I would like it to also show additional results (also part of the results from the same database).
Any idea how I do this? Just to clarify, it should not show until the ID is clicked to single out that entry - otherwise it shows them all in full one after the other.
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=***', '***', '***');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
class guestquestionnaireEntry {
public $id, $date_submitted,
$entry;
public function __construct()
{
$this->entry = "
<table border='1' align='center'>
<tr class='tablelist' style='font-size: 8pt;' ><td width='5%' colspan='2'>{$this->ID}</td><td width='40%' colspan='2'><b>Date Received: </b>{$this->date_submitted}</td><td width='45%' colspan='2'>{$this->name}</td><td width='10%'>View here </td></tr>
</table>
";
}
}
SELECT DATE_FORMAT(date_submitted, '%m/%d/%Y') AS date_submitted FROM guestquestionnaire
// Checks if the submitted is a number. If so, isolates the ID and adds "where" clause
$id = (!empty($_GET['ID']) && is_numeric($_GET['ID']))? " where ID = '".$_GET['ID']."'" : "";
// Add the $id to the end of the string
// A single call would be SELECT * FROM guestquestionnaire where ID = '1'
$query = $handler->query("SELECT * FROM guestquestionnaire{$id}");
$query->setFetchMode(PDO::FETCH_CLASS, 'guestquestionnaireEntry');
while($r = $query->fetch()) {
echo $r->entry, '<br>';
}
?>
Additional code that I would like to show once 'View Here' is clicked (so when the individual entry is shown):
class guestquestionnaireEntry {
public $id, $date_submitted, $choice, $expectations, $res, $res_information, $res_staff, $further_comments1,
$entry;
public function __construct()
{
$this->entry = "
<tr style='font-size: 8pt;'><td width='60%'>ID </td><td width='40%' colspan='2'>{$this->date_submitted}</td></tr>
<tr style='text-align: left; font:arial;'><td><h3>Date Submitted: {$this->date_submitted}</h3></td></tr>
<table border='1' align='center'>
<tr style='background: #566890; font-size: 8pt; font-weight: bold; color: #fff;'><td colspan='3'>Prior to Arrival</td></tr>
<tr style='font-size: 8pt;'><td width='60%'>What made you choose us for your recent trip? </td><td width='40%' colspan='2'>{$this->choice}</td></tr>
<tr style='font-size: 8pt;'><td>Did we meet your expectations as advertised? If no, please state why: </td><td width='40%' colspan='2'>{$this->expectations}</td></tr>
<tr style='background: #566890; font-size: 8pt; font-weight: bold; color: #fff;'><td colspan='3'>Making your Reservation</td></tr><BR>
<tr style='font-size: 8pt;'><td>Ease of making your reservation: </td><td width='40%'>$img</td><td width='5%'>{$this->res}</td></tr><BR>
<tr style='font-size: 8pt;'><td>Hotel information offered: </td><td width='40%'>$img2</td><td width='5%'>{$this->res_information}</td></tr><BR>
<tr style='font-size: 8pt;'><td>Warmth and friendliness of staff: </td><td width='40%'>$img3</td><td width='5%'>{$this->res_staff}</td></tr><BR>
<tr style='font-size: 8pt;'><td colspan='3'>Further Comments: </BR></BR>{$this->further_comments1}</td></tr>
<BR>
</table>
<BR>
<p>Back to List</p>
";
See if this works. I have not tested it, so make sure you save a copy of whatever you have so far. It requires database credentials to be filled out:
Classes:
<?php
interface Database
{
public static function SetConnection($host,$username,$password,$database);
}
interface Questionnaire
{
public function Display();
public function DisplaySingle();
}
class MySQLConn implements Database
{
protected static $host;
protected static $username;
protected static $password;
protected static $database;
public static $connect;
private function __construct()
{
}
public static function SetConnection($host = "***",$username = "***",$password = "***",$database = "***")
{
self::$host = $host;
self::$username = $username;
self::$password = $password;
self::$database = $database;
self::$connect = (!isset(self::$connect))? self::Initialize() : self::$connect;
}
private static function Initialize($use = 'PDO')
{
if($use == 'PDO') {
try {
$con = new PDO('mysql:host='.self::$host.';dbname='.self::$database, self::$username, self::$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $con;
}
catch (PDOException $e) {
die($e->getMessage());
}
}
else
return new mysqli(self::$host, self::$username, self::$password, self::$database);
}
}
class guestquestionnaireEntry implements Questionnaire
{
public $id,
$date_submitted,
$choice,
$expectations,
$res,
$res_information,
$res_staff,
$further_comments1,
$entry;
public function __construct()
{
if(empty($_GET['focus']))
$this->entry = $this->DisplaySingle();
else
$this->entry = $this->Display();
}
public function DisplaySingle()
{
ob_start(); ?>
<table border='1' align='center'>
<tr class='tablelist' style='font-size: 8pt;' >
<td width='5%' colspan='2'><?php echo $this->ID; ?></td>
<td width='40%' colspan='2'><b>Date Received: </b><?php echo $this->date_submitted; ?></td>
<td width='45%' colspan='2'><?php echo $this->name; ?></td>
<td width='10%'>View here</td>
</tr>
</table>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
public function Display()
{
ob_start(); ?>
<tr style='font-size: 8pt;'>
<td width='60%'>ID</td>
<td width='40%' colspan='2'><?php echo $this->date_submitted; ?></td>
</tr>
<tr style='text-align: left; font:arial;'>
<td><h3>Date Submitted: <?php echo $this->date_submitted; ?></h3></td>
</tr>
<table border='1' align='center'>
<tr style='background: #566890; font-size: 8pt; font-weight: bold; color: #fff;'>
<td colspan='3'>Prior to Arrival</td>
</tr>
<tr style='font-size: 8pt;'>
<td width='60%'>What made you choose us for your recent trip? </td>
<td width='40%' colspan='2'><?php echo $this->choice; ?></td>
</tr>
<tr style='font-size: 8pt;'>
<td>Did we meet your expectations as advertised? If no, please state why: </td>
<td width='40%' colspan='2'><?php echo $this->expectations; ?></td>
</tr>
<tr style='background: #566890; font-size: 8pt; font-weight: bold; color: #fff;'>
<td colspan='3'>Making your Reservation</td>
</tr>
<BR>
<tr style='font-size: 8pt;'>
<td>Ease of making your reservation: </td>
<td width='40%'>$img</td>
<td width='5%'><?php echo $this->res; ?></td>
</tr>
<BR>
<tr style='font-size: 8pt;'>
<td>Hotel information offered: </td>
<td width='40%'><?php echo $img2; ?></td>
<td width='5%'><?php echo $this->res_information; ?></td>
</tr>
<BR>
<tr style='font-size: 8pt;'>
<td>Warmth and friendliness of staff: </td>
<td width='40%'><?php echo $img3; ?></td>
<td width='5%'><?php echo $this->res_staff; ?></td>
</tr>
<BR>
<tr style='font-size: 8pt;'>
<td colspan='3'>Further Comments: </BR>
</BR>
<?php echo $this->further_comments1; ?></td>
</tr>
<BR>
</table>
<BR>
<p>Back to List</p>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
?>
To use:
<?php
//**********************************************************************************
// Add the classes here by way of include() or just pasted at the top of the page...
//**********************************************************************************
// Start up the database connection
MySQLConn::SetConnection();
// Assign database connection
$handler = MySQLConn::$connect;
// Checks if the submitted is a number. If so, isolates the ID and adds "where" clause
$id = (!empty($_GET['ID']) && is_numeric($_GET['ID']))? " where ID = '".$_GET['ID']."'" : "";
// Add the $id to the end of the string
// A single call would be SELECT * FROM guestquestionnaire where ID = '1'
$query = $handler->query("SELECT * FROM guestquestionnaire{$id}");
$query->setFetchMode(PDO::FETCH_CLASS, 'guestquestionnaireEntry');
// Assign data
while($r = $query->fetch()) {
$setEntry[] = $r->entry;
}
// Implode with break
if(isset($setEntry))
echo implode("<br />",$setEntry);
?>

Create Dynamic Table in PHP

I'm faced with a very simple task but for some reason the solution is eluding me, probably because my PHP is not good.
I have a table that has 1 header which spans across 4 columns. In the first column it would be static data, (i.e. headers so to speak but only in the first column). What I need is to populate the 2nd column and so on based on the results returned. I'm building a table that when a product is compared it will populate a column with information related to the product
<table id="price-compare" class="device-compare" border="1">
<caption>Price</caption>
<?php
$rows = 3;
$cols = 4;
for($tr=1;$tr<=$rows;$tr++){
echo "<tr>";
for($td=1;$td<=$cols;$td++){
echo "<td>row: ".$tr." column: ".$td."</td>";
}
echo "</tr>";
}
?>
<tr>
<td class="left-header"><?php echo $phones->field('name'); ?></td>
<td><sup>$</sup><?php echo $phones_retail; ?></td>
</tr>
<tr>
<td class="left-header">Fuel Price</td>
<td><sup>$</sup><?php echo $phones_retail; ?></td>
</tr>
<tr>
<td class="left-header">2-yr Contract Price</td>
<td style="font-weight: bold; color:#1b75bb;"><sup>$</sup><?php echo $phones_contract; ?></td>
</tr>
</table>
So as you can see, I need the first column to remain unchanged and adding the data related to the product to subsequent columns.
try the below code, hope it helps you:
for($td=1;$td<=$cols;$td++){
echo "<td>row: ".$tr." column: ".$td."</td>";
}
replace the above code by below one:
for($td=1;$td<=$cols;$td++){
if($td == 1)
{
echo "<td>Static Data</td>";
}
else
{
echo "<td>row: ".$tr." column: ".$td."</td>";
}
}

Categories