Pagination in PHP not working on same page? - php

I am developing a job portal where i have search box in my index page and for that i tried for pagination but pagination is not working and also if we click number it displaying nothing
i can't figure out the mistakes, results displaying , numbers button, is working perfectly but when click on number it is displaying nothing Here is my code
<?php
if( $user->is_logged_in() ){ header('Location: /emprdash'); }
if( ! empty($_SESSION['uid']))
{
header('Location: /emdash');
}
?>
<div class="container">
<div class="row">
<div class="col-md-12">
<form action="" method="post" >
<div id="adv-search" class="input-group">
<input class="form-control" name="term" id="term" type="text" placeholder="Search for jobs" required />
<div class="input-group-btn">
<div class="btn-group"><button class="btn btn-primary" name="submit" type="submit" value="search" >Search</button></div>
</div>
</div>
</form>
</div>
</div>
</div>
<br/>
<br/>
<?php
if(isset($_POST['submit']))
{
$limit=1;
$p=$_GET['p']=="" ? 1:$_GET['p'];
$start=($p-1)*$limit;
$status='active';
$term = $_POST['term'];
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare("SELECT * FROM job WHERE status='active' AND ( jdesc LIKE '%".$term."%' OR jtitle LIKE '%".$term."%' OR duration LIKE '%".$term."%' OR budget LIKE '%".$term."%' OR keyskills LIKE '%".$term."%' OR jdate LIKE '%".$term."%' OR edate LIKE '%".$term."%' OR cdexmin LIKE '%".$term."%' OR cdexmax LIKE '%".$term."%' ) ORDER BY jid DESC LIMIT $start,$limit ");
$stmt->execute();
$rows = $stmt->rowCount();
?>
<?php if($rows>=1){ ?>
<table class="table table-responsive table-inverse table-hover table-striped" >
<thead>
<tr class="info">
<th> JobTitle</th>
<th>Duration</th>
<th>Budget</th>
<th>Key Skills</th>
<th>Posted Date</th>
<th>Expiry Date</th>
<th>Experience Minimum</th>
<th>Experience Maximum</th>
<th></th>
</tr>
</thead>
<tbody>
<?php while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$jid=$row['jid'];
$repl = '<span class="highlight">' . $term . '</span>';
?>
<tr class="success">
<td>
<p><?php echo ucwords(str_ireplace($term, $repl, $row['jtitle'])); ?></p>
</td>
<td>
<p><?php echo str_ireplace($term, $repl, $row['duration']); ?></p>
</td>
<td>
<p><?php echo str_ireplace($term, $repl, $row['budget']); ?></p>
</td>
<td>
<p><?php echo str_ireplace($term, $repl, $row['keyskills']); ?></p>
</td>
<td>
<p><?php $jdate=strtotime( $row['jdate']); echo str_ireplace($term, $repl, date('d/M/Y',$jdate)); ?></p>
</td>
<td>
<p><?php $edate=strtotime( $row['edate']); echo str_ireplace($term, $repl, date('d/M/Y',$edate)); ?></p>
</td>
<td>
<p><?php echo str_ireplace($term, $repl,$row['cdexmin']); ?></p>
</td>
<td>
<p><?php echo str_ireplace($term, $repl,$row['cdexmax']); ?></p>
</td>
<td>
<form method="POST" action="">
<input type="hidden" name="jid" value="<?php echo $jid; ?>" >
<center><button type="submit" name="apply" class="btn btn-outlined btn-primary" >Login to Apply</button></center>
</form>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php } else {
echo '<center><div class="well">No results to display</div></center>';} ?>
<?php
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare("SELECT * FROM job WHERE status='active' AND ( jdesc LIKE '%".$term."%' OR jtitle LIKE '%".$term."%' OR duration LIKE '%".$term."%' OR budget LIKE '%".$term."%' OR keyskills LIKE '%".$term."%' OR jdate LIKE '%".$term."%' OR edate LIKE '%".$term."%' OR cdexmin LIKE '%".$term."%' OR cdexmax LIKE '%".$term."%' ) ");
$stmt->execute();
$count= $stmt->rowCount();
$countP=(ceil($count/$limit)) + 1;
$tW=($countP*50) + $countP;
echo"<center style='overflow-x:auto;margin-top:10px;padding-bottom:10px;'>";
echo"<div style='width:".$tW."px'>";
for($i=1;$i<$countP;$i++){
$isC=$i==$_GET['p'] ? "b-green":"";
echo "<a href='?p=$i'><button class='pgbutton $isC'>$i</button></a>";
}
echo"</div>";
echo"</center>";
?>
<?php } ?>
<?php
if(isset($_POST['apply']))
{
$jobid=$_POST['jid'];
$_SESSION['url'] = "/applyjob?jid=$jobid";
header("Location:/login");
}
?>
<style>
.pgbutton{
width:45px;
margin:0px 5px;
}
</style>

The reason it's not working is because you are clicking a link <a href='?p=$i'> to get to the next page. Once you click that link you'll lose your $_POST values because you are no longer submitting a form.
You need to change your implementation maybe change the url on the page and use htaccess rewrite to store the search term in the url. Or store the search term in the session. so you'll always have the search term available.
You might want to put a hidden input
<input type="hidden" name="page" value="1" />
change your page links
dsfsdf
Then some JS - (please note this uses jquery javascript library)
<script>
$(function() {
$('a.page_link').click(function(event) {
event.preventDefault();
// update page input
$('input[name="page"]').val($(this).data('pagenumber'));
$('input[name="page"]').closest('form').submit();
return false;
}
</script>

Related

Filter not filtering

I am trying to make a filter for website of cars. I would like to be able to filter by color of car represented by exterior. I do this by Select Distinct from exterior colors to list all of the exterior colors.
<h6 class="text-info">Select Color</h6>
<ul class="list-group">
<?php
$sql="SELECT DISTINCT exterior FROM newcars ORDER BY exterior";
$result=$conn->query($sql);
while($row=$result->fetch_assoc()) {
?>
<li class="list-group-item">
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input product_check" name="" value="<?= $row['exterior']; ?>" id="exterior"><?= $row['exterior']; ?>
</label>
</div>
</li>
<?php
}
?>
</ul>
<div id="test">
<?php
$sql = "SELECT * FROM newcars";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo ("<a href='newcarindex.php?id={$row['id']}'><div class='car'>");
echo '
<tr>
<td>
<img src="data:image\jpeg;base64,'.base64_encode($row['photo']).'"/>
</td>
</tr>
';
echo "<h2 class=car-name>";
echo $row['name'];
echo "</h2>";
echo "<span class=stock>STOCK#";
echo $row['stock'];
echo "</span>";
echo "<h3 class=car-msrp>";
echo $row['msrp'];
echo "</h3>";
echo "</div></a>";
}
} else {
echo "There are no Comments!";
}
?>
</div>
action.php this page i link to get the the results from what color they select. But I still cannot get it filter to the results.
include 'dbh.php';
if(isset($_POST['action'])) {
$sql = "SELECT * FROM newcars WHERE class !=''";
if(isset($_POST['class'])) {
$class = implode("','", $_POST['class']);
$sql .="AND class IN('".$class."')";
}
if(isset($_POST['body'])) {
$body = implode("','", $_POST['body']);
$sql .="AND class IN('".$body."')";
}
if(isset($_POST['exterior'])) {
$exterior = implode("','", $_POST['exterior']);
$sql .="AND class IN('".$exterior."')";
}
$result = $conn->query($sql);
$output='';
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$output .='<a href='newcarindex.php?id={$row['id']}'><div class='car'>
<tr>
<td>
<img src="data:image\jpeg;base64,'.base64_encode($row['photo']).'"/>
</td>
</tr>
<h2 class=car-name>'.$row['name'].'</h2>
<span class=stock>STOCK#'.$row['stock'].'</span>
<h3 class=car-msrp>'.$row['msrp'].'</h3>
</div></a>'
}
} else {
$output ="<h3>No Results</h3>";
}
echo $output;
}
?>
First of all you need to wrap your checkboxes in a HTML form that will send data to action.php file:
<h6 class="text-info">Select Color</h6>
<form action="action.php">
<ul class="list-group">
<?php
$sql = "SELECT DISTINCT exterior FROM newcars ORDER BY exterior";
$result = $conn->query($sql);
while($row=$result->fetch_assoc()) {
?>
<li class="list-group-item">
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input product_check" name="" value="<?= $row['exterior']; ?>" id="exterior"><?= $row['exterior']; ?>
</label>
</div>
</li>
<?php
}
?>
</ul>
<input type="submit" value="Filter" />
</form>
<div id="test">
...
Then, in action.php file you need to revise your SQL query. At this moment, when you concatenate base $sql variable with the one from if(isset($_POST['exterior'])) condition, the query looks like:
SELECT * FROM newcars WHERE class !=''AND class IN( ...
making it invalid (notice no space between !='' and AND).
Then the while loop has mixed apostrophes and quotation marks, which makes PHP code invalid. It should look like this:
while($row=$result->fetch_assoc()){
$photo = base64_encode($row['photo']);
$output .= "<a href='newcarindex.php?id={$row['id']}'>
<div class='car'>
<tr>
<td>
<img src='data:image\jpeg;base64,{$photo}'/>
</td>
</tr>
<h2 class='car-name'>{$row['name']}</h2>
<span class='stock'>STOCK#{$row['stock']}</span>
<h3 class='car-msrp'>{$row['msrp']}</h3>
</div></a>";
}

multiple entry of products in the database - PHP

I explain briefly I created a table that shows all my products on video, where inside the container that contains it are two select, enclosed in a form, which pass values ​​in order to populate the table in my db, and everything works perfectly. The only thing though that when I select more than one product the db correctly registers only the last one selected from the checkbox,place my code in order to reach my goal, that of being able to insert more products(impianto_id_campagna),for the same customer id (cliente_id_campagna), and event id (id_campagna_cliente):
code:
<?php
$messaggio = "";
if (isset($_POST['submit'])) {
include '../connessione.php';
$id_campagna_cliente = $connessione->real_escape_string($_POST['id_campagna_cliente']);
$cliente_id_campagna = $connessione->real_escape_string($_POST['cliente_id_campagna']);
$impianto_id_campagna = $connessione->real_escape_string($_POST['impianto_id_campagna']);
$connessione->query("INSERT INTO campagne_cliente (
id_campagna_cliente,
cliente_id_campagna,
impianto_id_campagna)
VALUES (
'$id_campagna_cliente',
'$cliente_id_campagna',
'$impianto_id_campagna')");
$messaggio = "Registrazione Completata!";
}
?>
<main>
<?php
include '../connessione.php';
$query_string = "SELECT * FROM store_locator WHERE store_locator.id NOT IN (SELECT impianto_id_campagna FROM campagne_cliente)";
$query = mysqli_query($connessione, $query_string);
?>
<?php
include '../connessione.php';
$query_string = "SELECT * FROM clienti";
$clienti = mysqli_query($connessione, $query_string);
?>
<?php
include '../connessione.php';
$query_string = "SELECT * FROM campagne_cliente
INNER JOIN clienti
ON clienti.cliente_id = campagne_cliente.cliente_id_campagna
INNER JOIN campagne
ON campagne.id_campagna = campagne_cliente.id_campagna_cliente GROUP BY cognome";
$campagne = mysqli_query($connessione, $query_string);
?>
<!-- Datatables initialization -->
<script>
// Basic example
$(document).ready(function () {
$('#dtBasicExample').DataTable();
$('.dataTables_length').addClass('bs-select');
});
</script>
<!-- Structured data: Breadcrumbs -->
<form method="post" action="index.php">
<div class="container-fluid text-center">
<div class="row">
<div class="col-md-6">
<select name="cliente_id_campagna" class="ciao colorful-select dropdown-primary" multiple searchable="Cerca il Cliente">
<option value="" disabled selected>Cliente</option>
<?php
while($row = mysqli_fetch_assoc($clienti)){ ?>
<option value="<?php echo $row['cliente_id'] ;?>"><?php echo $row['nome'].' '.$row['cognome'] ;?></option>
<?php } ?>
</select>
<script type="text/javascript">
// Material Select Initialization
$(document).ready(function() {
$('.ciao').material_select();
});
</script>
</div>
<div class="col-md-6">
<select name="id_campagna_cliente" class="ok colorful-select dropdown-primary" multiple searchable="Cerca la campagna">
<option value="" disabled selected>Cliente</option>
<?php
while($row = mysqli_fetch_assoc($campagne)){ ?>
<option value="<?php echo $row['id_campagna_cliente'] ;?>"><?php echo $row['nome'].' '.$row['cognome'].' INIZIO['.$row['data_inizio'].'] FINE['.$row['data_fine'].']' ;?></option>
<?php } ?>
</select>
<script type="text/javascript">
// Material Select Initialization
$(document).ready(function() {
$('.ok').material_select();
});
</script>
</div>
</div>
<div class="col-md-12">
<?php if ($messaggio != "") echo $messaggio . "<br><br>"; ?>
<table id="dtBasicExample" class="table table-striped table-bordered table-sm" cellspacing="0" width="100%">
<thead>
<tr>
<th class="th-sm">ID
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Cimasa
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Proprietaria
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Concessionaria
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">City
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Latitudine
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Longitudine
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($query)){ ?>
<tr>
<td>
<!-- Material unchecked -->
<div class="form-check">
<input type="checkbox" name="impianto_id_campagna" class="form-check-input" value="<?php echo $row['id'] ;?>" id="<?php echo $row['id'] ;?>">
<label class="form-check-label" for="<?php echo $row['id'] ;?>"></label>
</div>
</td>
<td><?php echo $row['cimasa'] ;?></td>
<td><?php echo $row['proprietaria'] ;?></td>
<td><?php echo $row['concessionaria'] ;?></td>
<td><?php echo $row['city'] ;?></td>
<td><?php echo $row['lat'] ;?></td>
<td><?php echo $row['lng'] ;?></td>
</tr>
<?php } ?>
</tfoot>
</table>
<input class="btn btn-primary" name="submit" type="submit" value="Register..."><br>
</form>
</div>
</div>
It register only the last one selected product because you have the same name attribute for every checkbox. Set the name to impianto_id_campagna[] in order to return an array in your $_POST variable.
<input type="checkbox" name="impianto_id_campagna[]" class="form-check-input" value="<?php echo $row['id'] ;?>" id="<?php echo $row['id'] ;?>">
Then you loop all your checkbox values inserting one product at a time:
<?php
$id_campagna_cliente = $connessione->real_escape_string($_POST['id_campagna_cliente']);
$cliente_id_campagna = $connessione->real_escape_string($_POST['cliente_id_campagna']);
foreach ($_POST['impianto_id_campagna'] as $value)
{
$impianto_id_campagna = $connessione->real_escape_string($value);
$connessione->query("INSERT INTO campagne_cliente (
id_campagna_cliente,
cliente_id_campagna,
impianto_id_campagna)
VALUES (
'$id_campagna_cliente',
'$cliente_id_campagna',
'$impianto_id_campagna')");
$messaggio = "Registrazione Completata!";
}
Checkbox items are passed as an array. In order to get them in to the database, you have to loop through the array and act accordingly.
foreach($impianto_id_campagna as $row){
//Iterate through and do what you need to do with the data.
}

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'];

Pass ID of row to Detail Page with PDO

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.

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.

Categories