Pass ID of row to Detail Page with PDO - php

I'm trying to update a master/detail setup from mysql to PDO in order to be compatible with PHP7. I have got the master page working exactly as it should - it produces a table that lists audio files and when you click on a title the idea is that you are taken to a detail page where the audio player is displayed. I am having trouble coding the detail page so that the ID from the master page is passed to the detail page and displays title and author together with the HTML5 audio player.
Here is the code for the master page:
<?php
$doc->addScript(JURI::root(true).'/templates/nfhop/js/sorttable.js' )
?>
<?php
require_once JPATH_SITE.'/includes/dbAudio.php'; ?>
<?php $query = $handler->query('SELECT * from audio ORDER BY subject ASC'); ?>
<article class="left">
<div class="formwrap">
<table class="members-audiolist table-striped sortable" border="0" align="left">
<thead>
<tr class="audio_header">
<td><p class="house-red">Subject</p></td>
<td><p class="house-red">Title</p></td>
<td><p class="house-red">Author</p></td>
</tr>
</thead>
<?php
while($r = $query->fetch(PDO::FETCH_OBJ)) { ?>
<tbody>
<tr>
<td width="25%"><?php echo $r->subject; ?></td>
<td> <?php echo $r->title; ?></td>
<td><?php echo $r->author; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="clearfix"></div>
</div>
<div style="margin-left:18px">
<p style="margin-top: 8px; font-size: 1em">To listen: click on title</p>
<p style="font-size: 1em">To download: right click on title and select save link as...</p>
<p style="font-size: 1em">You can sort by subject, title or author, just click on heading at top of column</p>
</div>
</article>
And this is my attempt at code for the detail page:
<?php
require_once JPATH_SITE.'/includes/dbAudio.php';
$query = $handler->query('SELECT * FROM audio WHERE id = ?'); ?>
?>
<hr class="divider" />
<h2><?php echo $r->title; ?> </h2>
<p>Speaker: <?php echo $r->author; ?> </p>
<p><?php echo $r->date; ?> </p>
<p><span style="font-style: italic">Category: <?php echo $r->subject; ?> </p><br />
<audio controls>
<source src="http://media.nfhop.org/<?php echo $r->audio_location; ?>" type="audio/mp3">
</audio>
<p class="margin-T10"> <img src="http://www.nfhop.org/<?php echo $r->image; ?>"></p>
<p>return to audio list
Would be grateful for any assistance in getting this to work!

If $handler is an instance of PDO you could do it like this:
<?php
require_once JPATH_SITE.'/includes/dbAudio.php';
// Audio id is stored in `$_GET['recordID']`
$stmt = $handler->prepare('SELECT * FROM audio WHERE id = ?');
$stmt->bindParam(1, $_GET['recordID']);
$stmt->execute();
$r = $stmt->fetch(PDO::FETCH_OBJ);
print_r($r);?>
According to what properties are there in $r you can output them.

Related

Creating Bootstrap Accordionin in a while loop

I'm trying to create a dynamic content field where each data is in a separate accordion and am having a bit of trouble.
Result is the first accordion only works even i am having different id's for each accordion.
Can anyone help me on this
while ($row = mysqli_fetch_assoc($sql_result))
{
$i=1;
?>
<div class="container-fluid border">
<table width=100%>
<tr>
<td><img src="/images/vehicles/<?php echo strtolower($row['vtype']); ?>.jpg" width="75" heigth="75" alt=""></td>
<td align="center"><b><?php echo $row['vtype']; ?> A/C </b> - <?php echo $row['nos']; ?> Seater<br>
<b>₹ <?php if($duration=='8hrs') { $basefare=$row['8hrs']; } elseif($duration=='10hrs') { $basefare=$row['10hrs']; } else { $basefare=$row['12hrs']; } $base=$basefare+($basefare*5/100); echo number_format($base,2,".",","); ?> </b></td>
<td align="right">Book</td>
</tr>
</table>
</div>
<div id="accordionfare<?php echo $i; ?>">
<div class="card">
<div class="card-header" align="right">
<a class="card-link" data-toggle="collapse" href="#collapsefare<?php echo $i; ?>">Fare Details</a>
</div>
<div id="collapsefare<?php echo $i; ?>" class="collapse" data-parent="#accordionfare<?php echo $i; ?>">
<div class="card-body">
<p align="center"><b>Fare Details: </b>Base Fare: ₹ <?php echo number_format($basefare,2,".",","); ?> | GST # 5%: ₹ <?php echo number_format(round($base*5/100),2,".",","); ?> | Extra Hr Fare: ₹ <?php echo number_format($row['extrahr'],2,".",","); ?>/Hr | Extra Km Fare: ₹ <?php echo number_format($row['extrakm'],2,".",","); ?>/Km</p>
<?php $i++; ?>
</div>
</div>
</div>
</div><br>
<?php
}
?>
I've tested your code replacing your data and it works as expected. Check you PHP error log in case there are errors which might brake the loop in some way.
Here is a sandbox where you can Execute my test code and check the HTML result
P.S. You must have accordions with different ids in order to open each one separately.

DIsplaying posts only created by specific user on his own dashboard

Displaying posts by specific user? this i saw is for ruby on rails and it couldn't help me..
I have two tables, users and posts.
If a user posts anything, it displays on his dashboard which works fine for now. But what i need is for the user to view only his posts.
Please help...
Below is my code:
server.php
<?php
// connect to database
require_once 'database.php';
// initialize variables
$note = "";
$id = 0;
$edit_state = false;
// if save button is clicked
if (isset($_POST['save'])) {
$note = addslashes($_POST['note']);
$created_at = date("Y-m-d H:i:s");
// basic first name validation
if (empty($note)) {
$error = true;
$noteError = "Field cannot be empty.";
}else {
// insert records if no error
$query = "INSERT INTO posts (note, created_at, updated_at) VALUES ('$note', '$created_at', NOW())";
mysqli_query($dbconn, $query);
$_SESSION['msg'] = "Saved";
header('location: ../home.php'); // redirect to home page after inserting
}
}
?>
and this is home.php where results are displayed
<?php
ob_start();
session_start();
error_reporting(E_ALL);
require_once 'config/database.php';
include 'config/server.php';
// if session is not set this will redirect to login page
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
// select loggedin users detail
$res=mysqli_query($dbconn, "SELECT * FROM users WHERE Id=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
?>
<div class="container" style="margin-top: 100px;">
<div class="row">
<div class="col-sm-6">
<div class="wrap-status100">
<form method="post" class="login100-form validate-form" action="config/server.php" autocomplete="off">
<span class="login100-form-title p-b-26">
<?php if (isset($_SESSION['msg'])): ?>
<div class="form-group">
<div class="alert alert-<?php echo $_SESSION['msg']; unset($_SESSION['msg']); ?>">
<span class="glyphicon glypicon-info-sign"></span>
</div>
</div>
<?php endif ?>
What's up <?php echo $userRow['fname']; ?>?
</span>
<div class="wrap-input100 validate-input">
<textarea name="note" class="input100" value="<?php echo $note; ?>"></textarea>
<span class="focus-input100" data-placeholder="Write note here."></span>
</div>
<div class="container-login100-form-btn">
<div class="wrap-login100-form-btn">
<div class="login100-form-bgbtn"></div>
<?php if ($edit_state == false): ?>
<button name="save" class="login100-form-btn">
Save
</button>
<?php else: ?>
<button name="update" class="login100-form-btn">
Update
</button>
<?php endif ?>
</div>
</div>
</div>
</form>
</div>
<div class="col-sm-6">
<?php if (isset($_SESSION['msg'])): ?>
<div class="msg">
<?php
echo $_SESSION['msg'];
unset($_SESSION['msg']);
?>
</div>
<?php endif ?>
<table>
<thead>
<tr>
<th>Note</th>
<th>created</th>
<th>Updated</th>
<th colspan="2">Action</th>
</tr>
</thead>
<tbody>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['note']; ?></td>
<td><?php echo $row['created_at']; ?></td>
<td><?php echo $row['updated_at']; ?></td>
<td><a class="edit_btn" href="home.php?update=<?php echo $row['id']; ?>">Update</a>
</td>
<td>
<a class="del_btn" href="config/server.php?del=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
You need to take one more column in posts table i.e user_id. You have to store the id of user who create the Post.
While fetching the result, you can take logged in user's id. And create a query like
"Select * from posts where user_id=".$_SESSION['user'];
by this you have get all the posts created by that particular user.
Hope this helps.
Thanks.
You need to do this in this way:
First while adding a post you have to insert the user id of the user who is posting the post. Be sure to add a field named user_id in the posts table in db. PLease try this query:
$user_id=trim($_SESSION['user']);
$query = "INSERT INTO posts (note,user_id, created_at, updated_at) VALUES ('$note', '".$user_id."' , '$created_at', NOW())";
Now in the dashboard of the user you need to fetch the posts based on the user_id and then loop the tr in the results array:
"Select * from posts where user_id=".$_SESSION['user'];

PHP Displaying data from database into a table when a link is clicked

Just to start off, I am new to php so i might have missed something obvious so please bear with me.
I have hyperlinks (planes, ships trains etc) and when I click the hyperlink "planes" i want all of the planes records to be displayed in a table. When I click a different vehicle i want it to refresh the table with new data.
The problem is, when i click the link "trains" it does not refresh the table and display relevant data, it keeps the same data. How do i tell php when i click the link "planes" i want to display all the records with that productLine.
Thanks for any help
As you can see in the pic, i clicked train but it still displays vintage cars
Here is my code:
<?php
require_once('dbconfig.php');
//get productLine
if (!isset($productLine)) {
$productLine = filter_input(INPUT_GET, 'productLine', FILTER_VALIDATE_INT);
if ($productLine == null || $productLine == FALSE) {
$productLine = 'Trains';
}
}
//get all product lines
$query = 'SELECT * FROM productlines';
$statement = $db->prepare($query);
$statement->execute();
$productLines = $statement->fetchAll();
$statement->closeCursor();
//Get products for product line
$queryProducts = 'SELECT * FROM products WHERE productLine = :productLine ORDER BY productCode';
$statement1 = $db->prepare($queryProducts);
$statement1->bindValue(':productLine', $productLine);
$statement1->execute();
$products = $statement1->fetchAll();
$statement1->closeCursor();
?>
<!DOCTYPE html>
<html>
<head>
<title>Classic Models Online</title>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>
<body>
<header><h1>ClassicModels Online</h1>
<p>Classic models for all automobile enthusiasts</p>
</header>
<main>
<h1>Classic Models Product List</h1>
<aside>
<!--Display list of product lines-->
<h2>Product Lines</h2>
<nav>
<ul>
<?php foreach ($productLines as $productLine) : ?>
<li>
<a href=".?productLine=<?php echo $productLine['productLine']; ?>">
<?php echo $productLine['productLine']; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</nav>
</aside>
<br>
<section>
<!--Display a table of products for product line-->
<h2><?php echo $productLine['productLine']; ?></h2>
<table>
<tr>
<th>Code</th>
<th>Name</th>
<th>Scale</th>
<th>Price</th>
<th>Total Sold</th>
<th> </th>
</tr>
<?php foreach ($products as $product) :?>
<tr>
<td> <?php echo $product['productCode']; ?> </td>
<td> <?php echo $product['productName']; ?> </td>
<td> <?php echo $product['productScale']; ?> </td>
<td> <?php echo $product['MSRP']; ?> </td>
<td> <?php echo $product['quantityInStock']; ?> </td>
<td> <form action="update_product.php" method="post">
<input type="hidden" name="productCode" value="<?php echo $product['productCode']; ?>">
<input type ="hidden" name="productLine" value="<?php echo $product['productLine']; ?>">
<input type="submit" value="Update">
</form> </td>
</tr>
<?php endforeach; ?>
</table>
<p>Add Product</p>
</section>
</main>
<footer>
<p>© <?php echo date("Y"); ?> Classic Models Online.</p>
</footer>
</body>
</html>
You need to get the productLine variable from the query string you have in the url. You need to add something like
if(isset($_GET['productLine'])){
$productLine = $_GET['productLine'];
}
Just do if(isset($_GET["productLine"])){//do your stuff}

data insert into database automatically in php

I have a problem which is the user when write in my comments form is insert successfully but when I refresh the page it will insert the last comments again , I read the solution in this link how to stop data automatically insert into database in php
but does not work for me
this is my codes I would appreciate for your help :)
file viewhospital.php contain include comments.php file
--look at the bottom of the codes--
<?php
include ('header.php');
if(!isset($_GET['hospital_id'])){
echo '<div class="alert alert-danger" role="alert"><b>You should choose hospital before opening this page!</b></div>';
include ('footer.php');
die();
}
include ('setting.php');
$sql = 'select * from hospital where hid = '. $_GET['hospital_id'];
$result = $conn->query($sql) or die(mysql_error($conn));
$hospital = null;
if ($result->num_rows > 0) {
$hospital = $result->fetch_assoc();
} else {
die('Could not find hospital!');
}
$sql = 'select * from doctor where hospital_id = '. $_GET['hospital_id'];
$doctor_result = $conn->query($sql) or die(mysql_error($conn));
$conn->close();
?>
<div class="row">
<div class="col-md-6">
<p class="text-center">
<img src="<?php echo $hospital['image']; ?>" class="img-thumbnail" style="height: 400px;">
</p>
</div>
<div class="col-md-6">
<p class="text-center">
<img class="img-thumbnail" src="https://maps.googleapis.com/maps/api/staticmap?center=<?php echo $hospital['location']; ?>&zoom=13&size=400x400&maptype=roadmap&markers=color:blue%7Clabel:S%7C<?php echo $hospital['location']; ?>&key=AIzaSyD59nHXpZgqZwjJvsAcPe2CYcIEWoaQ9yY" style="height: 400px;">
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h1 class="page-header">
<?php echo $hospital['name']; ?>
</h1>
<p>
<?php echo $hospital['description']; ?>
</p>
<p>
Address: <?php echo $hospital['address']; ?>
</p>
<p>
Phone: <?php echo $hospital['phone']; ?>
</p>
<p>
Go To Hospital
</p>
<p>
Online Appointment
</p>
</div>
</div>
<!--<div class="row">
<div class="col-md-12 text-center">
<div class="btn-group" role="group" aria-label="...">
<a type="button" class="btn btn-info">Edit</a>
<a type="button" class="btn btn-danger">Remove</a>
<a type="button" class="btn btn-primary" href="doctor_form.php?hospital_id=<?php echo $hospital['hid']; ?>">Add Doctor</a>
</div>
</div>
</div>-->
<div class="row">
<div class="col-md-12">
<table class="table table-striped">
<caption>Doctors:</caption>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Field</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
if ($doctor_result->num_rows > 0) {
while($row = $doctor_result->fetch_assoc()) {
?>
<tr>
<th scope="row">
<?php echo $row['did'];?>
</th>
<td>
<?php echo $row['name'];?>
</td>
<td>
<?php echo $row['field'];?>
</td>
<td>View</td>
</tr>
<?php
}
}else{
?>
<tr>
<th scope="row"></th>
<td>No doctors found</td>
<td></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<?php
include ('comments.php');
include ('footer.php');
?>
the comments.php file
<?PHP
# comments PHP code
date_default_timezone_set('Asia/Riyadh');
function setComments (){
if (isset($_POST['submitComments'])){
include('setting.php');
//$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments ( date, message) VALUE ( '$date', '$message')";
$result = mysqli_query($conn,$sql);
}
}
function getComments (){
if (isset($_POST['submitComments'])){
include('setting.php');
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn,$sql);
while ($row = $result->fetch_assoc()){
echo "<div class='comments-box'>";
echo $row['date']."<br>";
echo nl2br($row['message'])."<br><br>";
echo "</div>";
}
}
}
echo "
<form action='".setComments ()."' method='POST'>
<input type='hidden' name='uid' value=''>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message' class='form-control' rows='3'></textarea>
<br>
<button type='submit' name='submitComments' class='btn btn-primary'>Comments</button>
</form>
<br><br>
";
getComments ();
?>
When you refresh in the browser, you send the last request again. That request was the POST of the form. So the user (browser) is telling the code to insert another comment.
Generally this is handled by redirecting after posting a form, rather than re-displaying the form again. Move all of your logic for (and only for) inserting the new content to its own PHP file (something like addComment.php) and have the form post to that file. Then in that file ensure that there is no actual output except perhaps to display an error message if something goes wrong?) and just a redirect back to the page:
header("Location: viewhospital.php");
This will instruct the browser in the response to make a new GET request for viewhospital.php. So if the user reloads the browser, all they're doing is repeating that GET request.

How to present table in gallery view using jquery or php

I'm trying to create a system wherein the users can view records in the database, and its corresponding image. My problem is how to present the table in a fashion similar to that of ebay:
Here's my code:
<?php
require_once('header.php');
?>
<?php $list_items = $db->get_results("SELECT * FROM tbl_products"); ?>
<table border="1">
<?php foreach($list_items as $k=>$li){ ?>
<tr>
<td>
<p>
<img src="../img/items/<?php echo $li->str_filename; ?>" width="150px" height="150px">
</p>
<p>
Product Name: <?php echo $li->str_productName; ?>
</p>
<p>
Category: <?php echo $li->str_category; ?>
</p>
<p>
Quantity: <?php echo $li->dbl_qty; ?>
</p>
<p>
Price: <?php echo $li->dbl_price; ?>
</p>
</td>
</tr>
<?php } ?>
</table>
The current code is outputting the records in list view. Wherein, there's only one record per row. What I want is 4-6 records per row. How do I do that?
try this
<table border="1">
<?php
$intMaxColumn=4;
$intCountColumn=1;
foreach($list_items as $k=>$li){
if($intCountColumn==1){
?>
<tr>
<?php
}
?>
<td>
<p>
<img src="../img/items/<?php echo $li->str_filename; ?>" width="150px" height="150px">
</p>
<p>
Product Name: <?php echo $li->str_productName; ?>
</p>
<p>
Category: <?php echo $li->str_category; ?>
</p>
<p>
Quantity: <?php echo $li->dbl_qty; ?>
</p>
<p>
Price: <?php echo $li->dbl_price; ?>
</p>
</td>
<?php
if($intCountColumn==$intMaxColumn){
$intCountColumn=1;
?>
</tr>
<?php
}else{
$intCountColumn++;
}
}
?>
</table>
add CSS to these tables:
float:left;
and it will be the same
and do not include one table, but new table for each item. Try this
<?php
require_once('header.php');
$list_items = $db->get_results("SELECT * FROM tbl_products");
foreach($list_items as $k=>$li){
?>
<table border="1" style="float:left;">
<tr>
<td>
<p>
<img src="../img/items/<?php echo $li->str_filename; ?>" width="150px" height="150px">
</p>
<p>
Product Name: <?php echo $li->str_productName; ?>
</p>
<p>
Category: <?php echo $li->str_category; ?>
</p>
<p>
Quantity: <?php echo $li->dbl_qty; ?>
</p>
<p>
Price: <?php echo $li->dbl_price; ?>
</p>
</td>
</tr>
</table>
<?php } ?>
demo

Categories