data insert into database automatically in php - 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.

Related

MySQL on PHP need 2 reloads to update the values

I made a message deleter button, but I need 2 reloads to appear the changes...
(The rest of the code work, so it's normal that I don't show you the rest of the code...)
<?php while($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<div class="profile">
<img class="avatar" src="members/avatars/<?php if(empty(get_avatar($r['id_author']))) { echo "default.png"; } else { echo get_avatar($r['id_author']); } ?>" width="150" height="150">
<h3 style="text-align: center;"><?= get_username($r['id_author']) ?></h3>
</div>
<div class="content">
<div class="date">
<?= date('d F Y - g:iA', strtotime($r['date_hour_post'])) ?>
</div>
<br><br>
<?= htmlspecialchars_decode($r['content']) ?>
<form method="POST"><button name="delete<?= $r['id'] ?>">Test</button></form>
<?php
$test = "delete".$r['id'];
if(isset($_POST[$test])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($r['id']));
$success = "Your message was successfully removed !";
}
?>
</div>
</div>
<br>
<?php } ?>
UPDATE:
I added the deleting code at the top of my php code, and it's working, thanks to Ray Andison
By the way thanks to keidakida too; he helped me to find a solution to my value problem. (And I think he don't know that)
Your form doesn't contain any data (the id to be deleted) or action (page to submit data to)?
<form method="POST" action="thispage.php">
<input id="test" name="test" type="hidden" value="<?= $r['id'] ?>">
<input type="submit">
</form>
UPDATED:
<?
if(isset($_POST[id])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST[id]));
$success = "Your message was successfully removed !";
}
while($r = $replies->fetch()){
echo '
<div class="message" id="'.$r[id].'">
<div class="profile">
<img class="avatar" src="members/avatars/';
if(empty(get_avatar($r[id_author]))){
echo "default.png";
}else{
echo get_avatar($r[id_author]);
}
echo '
" width="150" height="150">
<h3 style="text-align:center;">
'.get_username($r[id_author]).'
</h3>
</div>
<div class="content">
<div class="date">
'.date('d F Y - g:iA', strtotime($r[date_hour_post])).'
</div>
<br>
<br>
'.htmlspecialchars_decode($r[content]).'
<form method="POST" action="thispage.php">
<input id="id" name="id" type="hidden" value="'.$r[id].'">
<input type="submit">
</form>
</div>
</div>';
}
?>
This is how I would code this, you need to change the action="thispage.php" to be the name of itself so it posts to itself, replace with the actual name of your php file
It is because the delete PHP code is at the bottom. Actions such as delete should be at the top of the HTML or while loops before presenting the data. SO try this:
<?php
if(isset($_POST["delete"])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST['delete']));
$success = "Your message was successfully removed !";
}
while($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<div class="profile">
<img class="avatar" src="members/avatars/<?php if(empty(get_avatar($r['id_author']))) { echo "default.png"; } else { echo get_avatar($r['id_author']); } ?>" width="150" height="150">
<h3 style="text-align: center;"><?= get_username($r['id_author']) ?></h3>
</div>
<div class="content">
<div class="date">
<?= date('d F Y - g:iA', strtotime($r['date_hour_post'])) ?>
</div>
<br><br>
<?= htmlspecialchars_decode($r['content']) ?>
<form method="POST">
<button type="button" name="delete" value="<?php echo $r['id']; ?>">Test</button>
</form>
</div>
</div>
<br>
<?php
}
?>
But you can do the same functionality without any page reload. Check AJAX PHP
Since it would be better and easier with AJAX, this is how it goes:
main.php
<?php
while ($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<?php echo htmlspecialchars_decode($r['content']) ?>
<button onclick="delete('<?php echo $r['id']; ?>')">Delete</button>
</div>
<br>
<?php } ?>
<script>
function delete(id) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("Delete successfully");
location.reload();
}
};
xmlhttp.open("POST", "delete.php", true);
// Mandatory for simple POST request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send id you want to delete
xmlhttp.send("id=" + id);
}
</script>
And make another PHP file name is delete.php like this:
<?php
include 'YOUR_DB_Connect.php';
if(isset($_POST["delete"])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST['delete']));
}
?>

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

How Do I Create a Vanity URL After Submit

Hello so I have a site setup to where users can submit projects and it adds it to a upload folder and the database for user download anyway I want to have it so once a user submits a new project it creates a URL like “sitename.com/projects.html?projectname” or something like that. My code is below.
P.S Everything on my site works just need to learn how to create the url.
projects.html: Mainly used to display the recent projects.
<?php include("includes/header.php"); ?>
<?php
include_once 'dbconnect.php';
// fetch files
$sql = "select filename, title, description from tbl_files LIMIT 4";
$result = mysqli_query($con, $sql);
?>
<div id="container">
<div class="wrapper">
<div id="content">
<h2>Recent Projects <button style="float: right;">New Project</button></h2>
<p><table class="table table-striped table-hover">
<thead>
<tr>
<th>#</th>
<th>File Name</th>
<th>Description</th>
<th>Download</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['description']; ?></td>
<td><a href="uploads/<?php echo $row['filename']; ?>" download>Download</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</p>
<div id="column">
<div class="holder">
<h2>Welcome!</h2>
<ul id="latestnews">
<li class="last"> <p><?php
session_start();
include_once "vendor/autoload.php";
$page = new membership\Page(1);
if ($page->isValid() == true){
echo "Hello " . $_SESSION["username"] . "!<br /><br />
<a href='logout.html'>Logout</a>\n";
} elseif ($page->isValid() == false) { echo "<center>Please <a href='login.php'>Log in</a> to share projects.<br /> <a href='register.php'>Need A Account?</a></center>";}
?><br />
</p>
<br /></p>
</li>
</ul>
</div>
</div>
<br class="clear" />
</div>
</div>
<?php
error_reporting(E_ALL & ~E_NOTICE);
include('includes/memberlistconfig.php');
// call this file only after database connection
require_once 'functions.php';
?>
<div id="container">
<div class="wrapper">
<div id="content">
<h2>Categories</h2>
<p>
<div class="height20"></div>
<?php echo $emsg; ?>
<article>
Click on one of the categories to see what’s inside.
<ul>
<?php
$res = fetchCategoryTreeList();
foreach ($res as $r) {
echo $r;
}
?>
</ul>
</article>
</div></p>
<br class="clear" />
</div>
</div>
<?php include("includes/footer.php"); ?>
new-project.html: Allows used to upload a new project.
<?php
include_once('includes/header.php'); ?>
<?php
include_once 'dbconnect.php';
// fetch files
$sql = "select filename from tbl_files";
$result = mysqli_query($con, $sql);
?>
<?php
session_start();
include_once "vendor/autoload.php";
$page = new membership\Page(1);
if ($page->isValid() == true) {
?>
<div id="container">
<div class="wrapper">
<div id="content">
<h2>New Project</h2>
<p><center>
<form action='upload.php' method='post' enctype='multipart/form-data'>
<legend>Select File to Upload:</legend>
<div class='form-group'>
Title: <br /><input type='text' name='title' maxlength="255"/><br /><br />
Description: <br /><textarea type='text' name='description' maxlength="2000"></textarea><br /><br />
<input type='file' name='file1' />
</div>
<div class='form-group'><br />
<input type='submit' name='submit' value='Upload' class='btn btn-info'/>
</div>
<?php if (isset($_GET['st'])) { ?>
<div class='alert alert-danger text-center'>
<?php
if ($_GET['st'] == "success") {
echo "File Uploaded Successfully!";
} else {
echo 'Invalid File Extension!';
}
?>
</div>
<?php } ?>
</form></center>
</p><?php } ?>
<br /></div>
</p>
<div id="column">
<div class="holder">
<h2>Project Upload Rules</h2>
<ul id="latestnews">
This is this rules you must follow for uploading a project.<br /><br />
- You must own the project / script.<br />
- Must be 100% clean / safe.<br />
- Code must be easy to read.<br />
- No outdated code.<br />
<br />
If you don’t follow the rules your account who be banned.
<br />
</p>
<br /></p>
</li>
</ul>
</div>
</div>
<br class="clear" />
</div>
</div>
<?php include_once('includes/footer.php'); ?>
upload.php: This file uploads the info to the database.
<?php include('dbconnect.php'); ?>
<?php
//check if form is submitted
if (isset($_POST['submit']))
{
$filename = $_FILES['file1']['name'];
//upload file
if($filename != '')
{
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$allowed = ['zip', 'rar', 'php', 'html', 'sql'];
//check if file type is valid
if (in_array($ext, $allowed))
{
// get last record id
$sql = 'select max(id) as id from tbl_files';
$result = mysqli_query($con, $sql);
if (count($result) > 0)
{
$row = mysqli_fetch_array($result);
$filename = ($row['id']+1) . '-' . $filename;
}
else
$filename = '1' . '-' . $filename;
//set target directory
$path = 'uploads/';
$created = #date('Y-m-d H:i:s');
move_uploaded_file($_FILES['file1']['tmp_name'],($path . $filename));
$title = '';
if(!empty($_POST['title']))
{
$title = mysqli_real_escape_string($con, $_POST['title']);
}
$description = '';
if(!empty($_POST['description']))
{
$description = mysqli_real_escape_string($con, $_POST['description']);
}
// insert file details into database
$sql = "INSERT INTO tbl_files(filename, created, title, description) VALUES('$filename', '$created', '$title', '$description')";
mysqli_query($con, $sql);
header("Location: new-project.html?st=success");
}
else
{
header("Location: new-project.html?st=error");
}
}
else
header("Location: new-project.html");
}
?>

Pagination in PHP not working on same page?

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>

Categories