Search not functiong using pdo - php

I have a project that I'm doing now and my project consist of CRUD functions and it works fine. My project also has its pagination and search function.
The pagination is working but the search function does not seem to work. What I want is, a search where I can search anything within my table like I want to search all the fields or maybe a live search. Can somebody please help me.
Dbconfig.php
<?php
$db_host = 'localhost'
$db_username = 'root';
$db_password = '';
$db_name = 'survey';
try{
$db_con = new PDO("mysql:host={$db_host};dbname={$dbname}",db_username,$db_password);
}
catch(PDOException $exception{
echo $exception->getMessage();
}
include_once 'class.paginate.php'
$paginate = new paginate($DB_con);
?>
Class.paging.php
<?php
class paginate{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
public function dataview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php echo $row['user_id']; ?></td>
<td><?php echo $row['username']; ?></td>
<td><?php echo $row['password']; ?></td>
<td><?php echo $row['province']; ?></td>
<!-- <td>visit</td> -->
</tr>
<?php
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
public function search($query)
{
$stmt=$this->db->prepare($query);
$query = '%' . $query . '%';
$stmt->bindparam('query', $query, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
if(empty($result) or $result == false)
return array();
else
return $result;
}
public function paging($query,$records_per_page)
{
$starting_position=0;
if(isset($_GET["page_no"]))
{
$starting_position= ($_GET["page_no"]-1)*$records_per_page;
}
$query2=$query." limit. $starting_position,$records_per_page";
return $query2;
}
public function paginglink($query,$records_per_page)
{
$self = $_SERVER['PHP_SELF'];
$stmt = $this->db->prepare($query);
$stmt->execute();
$total_no_of_records = $stmt->rowCount();
if($total_no_of_records > 0)
{
?><tr><td colspan="4" align="center"><?php
$total_no_of_pages=ceil($total_no_of_records/$records_per_page);
$current_page=1;
if(isset($_GET["page_no"]))
{
$current_page=$_GET["page_no"];
}
if($current_page!=1)
{
$previous =$current_page-1;
echo "<a href='".$self."?page_no=1'>First</a> ";
echo "<a href='".$self."?page_no=".$previous."'>Previous</a> ";
}
for($i=1;$i<=$total_no_of_pages;$i++)
{
if($i==$current_page)
{
echo "<strong><a href='".$self."?page_no=".$i."' style='color:red;text-decoration:none'>".$i."</a> </strong> ";
}
else
{
echo "<a href='".$self."?page_no=".$i."'>".$i."</a> ";
}
} if($current_page!=$total_no_of_pages)
{
$next=$current_page+1;
echo "<a href='".$self."?page_no=".$next."'>Next</a> ";
echo "<a href='".$self."?page_no=".$total_no_of_pages."'>Last</a> ";
}
?></td></tr><?php
}
}
}
Index.php
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="Bootstrap/bootstrap.css">
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<body>
<div id="search-wrapper">
<form name="search" method="GET" action="">
<table id="search" class="table-responsive">
<tr>
<input name="var1" type="text" id="search-box">
<button id="submit" name="submit" type="submit">Search</button>
</tr>
</table>
<?php
$query = "SELECT * FROM `login` WHERE (`username` like :query or `password` like :query) ";
$paginate->search($query)
?>
</form>
</div>
<div id="table-wrapper" class="table-responsive">
<table id="data" class="table table-striped table-hover">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Password</th>
<th>Actions</th>
</tr>
</thead>
<?php
$query = "SELECT * FROM login";
$records_per_page=20;
$newquery = $paginate->paging($query,$records_per_page);
$paginate->dataview($newquery);
$paginate->paginglink($query,$records_per_page);
?>
</table>
</div>
<div id="footer">
cleartuts.blogspot.com
</div>
</body>
</html>

Related

MySQL problem using php when trying to update table

I want to update my tbl_category. But when I click on the Update button, it does not show any error. But it does not update the value of tbl_category. I am sure it's very simple since I am a beginner i am not getting well what is wrong exactly so please help me.
Here is the script:
catlist.php
<?php include 'inc/header.php';?>
<?php include 'inc/sidebar.php';?>
<?php include("../classes/Category.php");?>
<?php
$cat = new Category();
if(isset($_GET['delcat'])){
$id = $_GET['delcat'];
//$id = preg_replace('/[^-a-zA-Z0-9_]/', '', $_GET['delcat']);
$delCat = $cat->delCatById($id);
}
?>
<div class="grid_10">
<div class="box round first grid">
<h2>Category List</h2>
<div class="block">
<?php
if(isset($delCat)){
echo $delCat;
}
?>
<table class="data display datatable" id="example">
<thead>
<tr>
<th>Serial No.</th>
<th>Category Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$getCat = $cat->getAllCat();
if($getCat){
$i = 0;
while($result = $getCat->fetch_assoc()){
$i++;
?>
<tr class="odd gradeX">
<td><?php echo $i;?></td>
<td><?php echo $result['catName'];?></td>
<td>Edit || <a onclick="return confirm('Are you sure to delete!')" href="?delcat=<?php echo $result['catId'];?>">Delete</a></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
setupLeftMenu();
$('.datatable').dataTable();
setSidebarHeight();
});
</script>
<?php include 'inc/footer.php';?>
catedit.php
<?php include 'inc/header.php';?>
<?php include 'inc/sidebar.php';?>
<?php include("../classes/Category.php");?>
<?php
/*if(!isset($_GET['catid']) || $_GET['catid'] == NULL){
//echo "<script>window.location = 'catlist.php'; </script>";
} else{
$id = $_GET['catid'];
}*/
$id = isset($_GET['catid']) ? $_GET['catid'] : '';
//$id = $_GET['catid'];
$cat = new Category();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$catName = $_POST['catName'];
$updateCat = $cat->catUpdate($catName,$id);
}
?>
<div class="grid_10">
<div class="box round first grid">
<h2>Update Category</h2>
<div class="block copyblock">
<?php
echo $id;
?>
<?php
if(isset($updateCat)){
echo $updateCat;
}
?>
<?php
$getCat = $cat->getCatById($id);
if($getCat){
while($result = $getCat->fetch_assoc()){
?>
<form action="catedit.php" method="post">
<table class="form">
<tr>
<td>
<input type="text" name="catName" value="<?php echo $result['catName'];?>" placeholder="Enter Category Name..." class="medium" />
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" Value="Update" />
</td>
</tr>
</table>
</form>
<?php
}
}
?>
</div>
</div>
</div>
<?php include 'inc/footer.php';?>
Category.php
<?php
include_once("../lib/Database.php");
include_once("../helpers/Format.php");
?>
<?php
class Category {
private $db;
private $fm;
public function __construct() {
$this->db = new Database();
$this->fm = new Format();
}
public function catInsert($catName){
$catName = $this->fm->validation($catName);
$catName = mysqli_real_escape_string($this->db->link , $catName);
if(empty($catName)){
$msg = "<span class='error'>Category field must not be empty !</span>";
return $msg;
} else{
$query = "INSERT INTO tbl_category(catName) VALUES('$catName')";
$catinsert = $this->db->insert($query);
if($catinsert){
$msg = "<span class='success'>Category Inserted Successfully</span>";
return $msg;
} else {
$msg = "<span class='error'>Category Not Inserted.</span>";
return $msg;
}
}
}
public function getAllCat(){
$query = "SELECT * FROM tbl_category ORDER BY catId DESC";
$result = $this->db->select($query);
return $result;
}
public function getCatById($id){
$query = "SELECT * FROM tbl_category WHERE catId = '$id'";
$result = $this->db->select($query);
return $result;
}
public function catUpdate($catName,$id){
$catName = $this->fm->validation($catName);
$catName = mysqli_real_escape_string($this->db->link , $catName);
$id = mysqli_real_escape_string($this->db->link , $id);
if(empty($catName)){
$msg = "<span class='error'>Category field must not be empty !</span>";
return $msg;
} else{
//$query = "UPDATE tbl_category
//SET
//catName = '$catName'
//WHERE catId = '$id'";
$query = "UPDATE tbl_category SET catName = '$catName' WHERE catId = '$id'";
$updated_row = $this->db->update($query);
if($updated_row){
$msg = "<span class='success'>Category Updated Successfully</span>";
return $msg;
} else {
$msg = "<span class='error'>Category Not Updated.</span>";
return $msg;
}
}
}
public function delCatById($id){
$query = "DELETE FROM tbl_category WHERE catId = '$id'";
$delData = $this->db->delete($query);
if($delData){
$msg = "<span class='success'>Category Deleted Successfully</span>";
return $msg;
}
else {
$msg = "<span class='error'>Category Not Deleted.</span>";
return $msg;
}
}
}
?>
Once your catedit.php form is submitted, PHP is not receiving 'id', which it needs to be able to execute catUpdate method.
You should have additional (hidden) field in your form which would be for $id. Then, you will take that one from POST as well. $_POST['id'];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$catName = $_POST['catName'];
$id = $_POST['id'];
$updateCat = $cat->catUpdate($catName,$id);
}
....
<form action="catedit.php" method="post">
<input type="hidden" id="i" name="id" value="<?php echo $id; ?>">

I want my button to change the Status set, but instead of changing it, goes to a href page instead

First off: There are no YouTube videos or tutorials for this as far as I know. I found some but they were JavaScript, but I have no knowledge of it so I can't do it in a very short time.
I recently posted the same question but altered my codes after some people's suggestions. I got a lot of errors instead of a solution...
Anyway, I have a picture of my site and what I want to do.
Site:
https://imgur.com/a/hcpuA
and here's a picture of what I want to do:
https://imgur.com/a/Vuuk9
And finally my codes are below, I cut down the HTML parts which isn't really necessary.
adduser.php:
<?php
session_start();
if (!isset($_SESSION['username']))
{
header('location: login.php');
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Manage users</title>
<link rel="icon" type="image/png" sizes="16x16" href="image/favicon-16x16.png">
<link rel="icon" type="image/png" sizes="32x32" href="image/favicon-32x32.png">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/table.css">
</head>
<body>
<?php include ("header.php"); ?>
<?php
require ("config.php");
?>
<form name="frmSearch" method="post" action="adduser.php">
<div class="table-container">
<div class="table-something">
<div class="table-header">
<span id="message"></span>
<h2>Admin List<span class="blink">_</span> </h2>
<input name="var1" type="text" id="var1" />
<input class="dede" type="submit" name="search" value="search" />
</div>
<div class="table-body">
<table class="table-hen">
<?php
if (isset($_POST['var1'])) {
$var1 = $_POST['var1'];
}
else {
$var1 = 1;
}
$sql= "SELECT user_id, fname, mname, lname, username, type, a_e_num, user_status FROM users WHERE a_e_num LIKE :search";
$stmt = $db->prepare($sql);
$stmt->bindValue(':search', '%' . $var1 . '%', PDO::PARAM_INT);
$stmt->execute();
if ($stmt->rowCount() > 0) {
?>
<tr>
<th>User Id</th>
<th>Name </th>
<th>Username</th>
<th>Employee # </th>
<th>User Type</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php
$result = $stmt->fetchAll();
foreach ($result as $row):
?>
<tr>
<td><?php echo $row['user_id']; ?></td>
<td><?php echo $row['fname']; ?> <?php echo $row['mname']; ?> <?php echo $row['lname']; ?> </td>
<td><?php echo $row['username']; ?></td>
<td><?php echo $row['a_e_num']; ?> </td>
<td><?php echo $row['type']; ?></td>
<td>
<?php if ($row['user_status']=='Enable') echo "Active";
if ($row['user_status']=='Disable') echo "Disabled" ?>
</td>
<td>
<?php
$user_id = $row['user_id'];
$status = '';
if ($row['user_status'] == 'Enable') {
$status = 'Enable';
}
else if ($row['user_status'] == 'Disable') {
$status = 'Disable';
}
?>
<?php
$user_id = $row['user_id'];
$status = $row['user_status'];
?>
<a class="archive" action="archive.php" onclick="
return confirm('Are you sure you want to <?php if ($row['user_status']=='Enable') echo "disable";
if ($row['user_status']=='Disable') echo "enable"?> this user account?')"
href="archive.php?user_id=<?= $user_id?>&status=<?=$status?>">
<?php if ($row['user_status']=='Disable')
echo "Unarchive";
if ($row['user_status']=='Enable')
echo "Archive" ?>
</a></td>
</tr>
<?php endforeach;
} else {
echo 'there is nothing to show';
}
?>
</table>
</form>
</div>
</div>
</div>
<br><h1></h1>
<br><h1></h1>
<br><h1></h1>
<br><h1></h1>
<br><h1></h1>
<?php include ("footer.php"); ?>
</body>
</html>
And here's my Archive.php:
<?php
require ("config.php");
$user_id= $_GET['user_id'];
$user_status = $_GET['user_id'];
$query = $db->prepare ("SELECT * FROM users WHERE user_id = :user_id, user_status = :user_status");
$query->bindParam(':user_id', $user_id);
$query->bindParam(':user_status',$user_status);
$query->execute();
if ($user_status=='Enable')
{
$sql = "UPDATE users SET user_status = 'Disable' WHERE user_id = :user_id";
}
if ($user_status=='Disable')
{
$sql = "UPDATE users SET user_status='Enable' WHERE user_id = :user_id";
}
if ($query->execute([':user_status'=>$user_status, ':user_id'=>$user_id])){
header("Location:adduser.php");
}
?>
First you need to clear your statement and separate your parameters like below.
Step 1:
Parameters are (Query String) which start with ? and more paramters will be followed by &
<?php
$user_id = $row['user_id'];
$status = '';
if ($row['user_status'] == 'Enable') {
$status = 'Enable';
} else if ($row['user_status'] == 'Disable') {
$status = 'Disable';
}
?>
<a href="archive.php?user_id=<?=$user_id?>&user_status=<?=$status?>">
IF your $row['user_status'] value is always same as conditional statement then you don't need condition simply follow assign variable.
<?php
$user_id = $row['user_id'];
$status = $row['user_status'];
?>
<a href="archive.php?user_id=<?=$user_id?>&status=<?=$status?>">
Step 2:
Then this
$id= $_GET['user_id'];
To
$user_id= $_GET['user_id'];
$user_status = $_GET['user_status'];
because your bind parameters take variable which is not defined in your Archive.php
$query->bindParam(':user_id', $user_id);
$query->bindParam(':user_status',$user_status);
EDIT 2:
change your ` where it start with
<td>
<?php
$user_id = $row['user_id'];
$status = $row['user_status'];
Just replace with below.
<td>
<?php
$user_id = $row['user_id'];
$status = $row['user_status'];
$btn_confirm = '';
if ($status == 'Enable') {
$btn_confirm = "disable";
} else if ($status == 'Disable') {
$btn_confirm = "enable";
}
?>
<a class="archive" onclick="return confirm('Are you sure you want to <?= $btn_confirm; ?> this user account?')"
href="Archive.php?user_id=<?= $user_id ?>&status=<?= $status ?>">
<?php if ($status == 'Disable') {
echo "Unarchive";
} else if ($status == 'Enable') {
echo "Archive"; }
?>
</a>
</td>
Note: your file name is Archive.php not archive.php this causing issue for blank page

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens no found

I've created a database with two tables. I connected this database with a PHP page for a small CRUD app.
To execute the CRUD operations, I've created a crud.class.php that hold all operations.
Operations on the first table (membri) work but into the second (articoli) they fail, in the update articoli page.
Simply, I've create the same PHP function for the first table for the second, but it send me back this error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
Here are my crud.class.php and edi_articoli.php page:
Class.crud.php:
class crud
{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
/***************************************** Crea Articoli******************************/
public function crea_articolo($data,$autore,$titolo)
{
try
{
$stmt = $this->db->prepare("INSERT INTO articoli(data,autore,titolo) VALUES(:data, :autore, :titolo)");
$stmt->bindparam(":data",$data);
$stmt->bindparam(":autore",$autore);
$stmt->bindparam(":titolo",$titolo);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
/***************************************** Update Articolo******************************/
public function getID_articoli($id)
{
$stmt = $this->db->prepare("SELECT * FROM articoli WHERE id=:id");
$stmt->execute(array(":id"=>$id));
$editRow=$stmt->fetch(PDO::FETCH_ASSOC);
return $editRow;
}
public function update_articoli($id,$data,$autore,$titolo)
{
try
{
$stmt=$this->db->prepare("UPDATE articoli SET data=:data,
autore=:autore,
titolo:titolo,
WHERE id=:id ");
$stmt->bindparam(":data",$data);
$stmt->bindparam(":autore",$autore);
$stmt->bindparam(":titolo",$titolo);
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
/***************************************** End Crea e aggiungi Articoli******************************/
/***************************************** Articoli******************************/
public function articoliview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php print($row['id']); ?></td>
<td><?php print($row['data']); ?></td>
<td><?php print($row['autore']); ?></td>
<td class="setWidth concat"><div><?php print($row['titolo']); ?></div></td>
<td align="center">
<i class="glyphicon glyphicon-eye-open"></i>
</td>
<td align="center">
<i class="glyphicon glyphicon-edit"></i>
</td>
<td align="center">
<i class="glyphicon glyphicon-remove-circle"></i>
</td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td>Non c'è nulla qui...</td>
</tr>
<?php
}
}
/***************************************** End Articoli******************************/
/***************************************** CREAZIONE UTENTI******************************/
/****************************************************************************************/
public function create($nome,$cognome,$brev_descr,$descrizione)
{
try
{
$stmt = $this->db->prepare("INSERT INTO membri(nome,cognome,brev_descr,descrizione) VALUES(:nome, :cognome, :brev_descr, :descrizione)");
$stmt->bindparam(":nome",$nome);
$stmt->bindparam(":cognome",$cognome);
$stmt->bindparam(":brev_descr",$brev_descr);
$stmt->bindparam(":descrizione",$descrizione);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function getID($id)
{
$stmt = $this->db->prepare("SELECT * FROM membri WHERE id=:id");
$stmt->execute(array(":id"=>$id));
$editRow=$stmt->fetch(PDO::FETCH_ASSOC);
return $editRow;
}
/***************************************** END CREAZIONE UTENTI******************************/
/***************************************** UPDATE UTENTI ******************************/
public function update($id,$nome,$cognome,$brev_descr,$descrizione)
{
try
{
$stmt=$this->db->prepare("UPDATE membri SET nome=:nome,
cognome=:cognome,
brev_descr=:brev_descr,
descrizione=:descrizione
WHERE id=:id ");
$stmt->bindparam(":nome",$nome);
$stmt->bindparam(":cognome",$cognome);
$stmt->bindparam(":brev_descr",$brev_descr);
$stmt->bindparam(":descrizione",$descrizione);
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
/***************************************** END UPDATE UTENTI ******************************/
/***************************************** DELETE UTENTI******************************/
public function delete($id)
{
$stmt = $this->db->prepare("DELETE FROM membri WHERE id=:id");
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
/***************************************** END DELETE UTENTI******************************/
/***************************************** VIEW UTENTI ******************************/
public function dataview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php print($row['id']); ?></td>
<td><?php print($row['nome']); ?></td>
<td><?php print($row['cognome']); ?></td>
<td class="setWidth concat"><div><?php print($row['brev_descr']); ?></div></td>
<td align="center">
<i class="glyphicon glyphicon-eye-open"></i>
</td>
<td align="center">
<i class="glyphicon glyphicon-edit"></i>
</td>
<td align="center">
<i class="glyphicon glyphicon-remove-circle"></i>
</td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td>Non c'è nulla qui...</td>
</tr>
<?php
}
}
/***************************************** END VIEW UTENTI ******************************/
/***************************************** Paging ******************************/
public function paging($query,$records_per_page)
{
$starting_position=0;
if(isset($_GET["page_no"]))
{
$starting_position=($_GET["page_no"]-1)*$records_per_page;
}
$query2=$query." limit $starting_position,$records_per_page";
return $query2;
}
public function paginglink($query,$records_per_page)
{
$self = $_SERVER['PHP_SELF'];
$stmt = $this->db->prepare($query);
$stmt->execute();
$total_no_of_records = $stmt->rowCount();
if($total_no_of_records > 0)
{
?><ul class="pagination"><?php
$total_no_of_pages=ceil($total_no_of_records/$records_per_page);
$current_page=1;
if(isset($_GET["page_no"]))
{
$current_page=$_GET["page_no"];
}
if($current_page!=1)
{
$previous =$current_page-1;
echo "<li><a href='".$self."?page_no=1'>Primo</a></li>";
echo "<li><a href='".$self."?page_no=".$previous."'>Precedente</a></li>";
}
for($i=1;$i<=$total_no_of_pages;$i++)
{
if($i==$current_page)
{
echo "<li><a href='".$self."?page_no=".$i."' style='color:red;'>".$i."</a></li>";
}
else
{
echo "<li><a href='".$self."?page_no=".$i."'>".$i."</a></li>";
}
}
if($current_page!=$total_no_of_pages)
{
$next=$current_page+1;
echo "<li><a href='".$self."?page_no=".$next."'>Prossimo</a></li>";
echo "<li><a href='".$self."?page_no=".$total_no_of_pages."'>Ultimo</a></li>";
}
?></ul><?php
}
}
/* paging */
}
Here my "update_articoli.php" page:
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-update']))
{
$id = $_GET['edit_articolo_id'];
$data = $_POST['data'];
$autore = $_POST['autore'];
$titolo = $_POST['titolo'];
if($crud->update_articoli($id,$data,$autore,$titolo))
{
$msg = "<br/><div class='alert alert-success'>
<strong>L'articolo è stato aggiornato correttamente!</strong>
</div>";
}
else
{
$msg = "<div class='alert alert-warning'>
<strong> C'è stato un errore durante l' aggiornamento dell' articolo !</strong>
</div>";
}
}
if(isset($_GET['edit_articolo_id']))
{
$id = $_GET['edit_articolo_id'];
extract($crud->getID_articoli($id));
}
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<div class="container">
<?php
if(isset($msg))
{
echo $msg;
}
?>
</div>
<div class="clearfix"></div>
<div class="container">
<h1>Modifica articolo</h1><hr>
<i class="glyphicon glyphicon-backward"></i> Torna alla lista articoli
<br/><br/>
<form method='post'>
<table class='table table-bordered'>
<tr>
<td>Data</td>
<td><input type='text' name='data' class='form-control' value="<?php echo $data; ?>" required></td>
</tr>
<tr>
<td>Autore</td>
<td><input type='text' name='autore' class='form-control' value="<?php echo $autore; ?>" required></td>
</tr>
<tr>
<td>Titolo</td>
<td><textarea name='titolo' rows="5" maxlength="100" class='form-control' required><?php echo $titolo; ?></textarea></td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-primary" name="btn-update">
<span class="glyphicon glyphicon-edit"></span> Aggiorna articolo
</button>
<i class="glyphicon glyphicon-backward"></i> CANCEL
</td>
</tr>
</table>
</form>
</div>
<?php include_once 'footer.php'; ?>
Thanks for support.

applying search or filter to table with pagination

hello kind sirs can you help me with this code. What i try to do is when i type something in the search box, ex. pending it will show the 5 pending reservation per page(5 rows of pending reservation). but when i try it, it shows all the pending reservation which is more than 10.
here is the image
i try something like this.. but it shows nothing
$query = "SELECT * FROM reservations WHERE CONCAT(firstname, lastname, reservationstatus)LIKE '%".$valueToSearch."%' LIMIT " . $this_page_first_result . ',' . $results_per_page";
Here is the whole code
<?php
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ERROR | E_PARSE);
session_start();
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "srdatabase";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$results_per_page = 5;
$select= "SELECT * FROM reservations";
$result = mysqli_query($conn, $select);
$number_of_results = mysqli_num_rows($result);
if(!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
$this_page_first_result = ($page-1)*$results_per_page;
$sql = "SELECT * FROM reservations LIMIT " . $this_page_first_result . ',' . $results_per_page;
$result = mysqli_query($conn, $sql);
$number_of_pages = ceil($number_of_results/$results_per_page);
?>
<div id="paging-div">
<?php
for($page=1;$page<=$number_of_pages;$page++)
{
echo '<a id="pagingLink" href="adminControl.php?page=' . $page . '">' . $page . '</a>';
}
?>
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
$query = "SELECT * FROM reservations WHERE CONCAT(firstname, lastname, reservationstatus)LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else
{
$query = "SELECT * FROM reservations";
$search_result = filterTable($query);
}
function filterTable($query)
{
$conn = mysqli_connect("localhost", "root", "", "srdatabase");
$filter_Result = mysqli_query($conn, $query);
return $filter_Result;
}
?>
</div>
<!DOCTYPE html>
<html>
<head>
<title>Admin Control</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="topnav" id="myTopnav">
Home
Speakers
About
Contact
Reservation
Sign Out
<?php echo $_SESSION['firstname']; ?>
Sign Up
Sign In
Admin control
☰
</div>
<br>
<br>
<br>
<br>
<h4 style="padding-left:10px; text-align:center;">Reservation List</h4>
<hr>
<form action="adminControl.php" method="POST">
<input type="text" name="valueToSearch" placeholder="type a value">
<input type="submit" name="search" value="Filter">
</form>
<br>
<br>
<div style="overflow-x:auto;">
<table class="reservations-table">
<tr>
<th class="thFirstName">First Name</th>
<th class="thLastName">Last Name</th>
<th class="thEmailAddress">Email Address</th>
<th class="thContactNumber">Contact Number</th>
<th class="thSpeaker">Speaker</th>
<th class="thTopic">Topic</th>
<th class="thLocation">Location</th>
<th class="thAudience">Audience</th>
<th class="thCount">Count</th>
<th class="thTime">Time</th>
<th class="thDate">Date</th>
<th class="thAction">Reservation Date</th>
<th class="thAction">Status</th>
<th class="thAction">Action</th>
<th class="thAction">Action</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['firstname'];?></td>
<td><?php echo $row['lastname'];?></td>
<td><?php echo $row['emailaddress'];?></td>
<td><?php echo $row['contactnumber'];?></td>
<td><?php echo $row['speaker'];?></td>
<td><?php echo $row['topic'];?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['audience'];?></td>
<td><?php echo $row['count'];?></td>
<td><?php echo $row['time'];?></td>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['reservationdate'];?></td>
<td><?php echo $row['reservationstatus'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</div>
<?php
$epr='';
$msg='';
if(isset($_GET['epr']))
$epr=$_GET['epr'];
if($epr=='delete')
{
$id=$_GET['id'];
$delete=mysqli_query($conn, "DELETE FROM reservations WHERE id=$id");
if($delete)
header('location:adminControl.php');
else
$msg='Error :'.mysqli_error();
}
?>
<?php
$epr='';
$msg='';
if(isset($_GET['epr']))
$epr=$_GET['epr'];
if($epr=='approve')
{
$id=$_GET['id'];
$approve=mysqli_query($conn, "UPDATE reservations SET reservationstatus='approved' WHERE id=$id");
header('location:adminControl.php');
}
?>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<script>
function ifAdmin()
{
document.getElementById("signIn").style.display = "none";
document.getElementById("signUp").style.display = "none";
document.getElementById("signOut").style.display = "block";
document.getElementById("adminControl").style.display = "block";
}
</script>
<script>
function ifNotAdmin()
{
document.getElementById("signIn").style.display = "none";
document.getElementById("signUp").style.display = "none";
document.getElementById("signOut").style.display = "block";
document.getElementById("adminControl").style.display = "none";
}
</script>
<script>
function ifNotLogin()
{
document.getElementById("user").style.display = "none";
document.getElementById("signOut").style.display = "none";
document.getElementById("adminControl").style.display = "none";
}
</script>
<?php
if (isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == true)
//if login
{
if($_SESSION['type'] == 1)
{
echo "<script type='text/javascript'>ifAdmin();</script>";
}
elseif($_SESSION['type'] == 0)
{
echo "<script type='text/javascript'>ifNotAdmin();</script>";
}
}
//if not login
else
{
echo "<script type='text/javascript'>ifNotLogin();</script>";
}
?>
<div id="footer" class="push">Copyright 2017</div>
</body>
</html>
... when i try it, it shows all the pending reservation which is more than 10.
That's because when you hit 2nd, 3rd, ... pages(after navigating from the 1st page), the $_POST array would be empty i.e. $_POST['search'] won't be set, and that's why else{...} part of the code will get executed every time you navigate to 2nd, 3rd, ... pages. Since you're not sending any sensitive data with the form, use GET instead of POST in the method attribute of the form, like this:
<form action="..." method="get">
and get the user inputted data like this:
if (isset($_GET['search'])) {
$valueToSearch = $_GET['valueToSearch'];
...
Subsequently, you need to attach that search query in each of your pagination links, so that the search query would be available when you hop from page to page.
// your code
<?php
for($page=1;$page<=$number_of_pages;$page++)
{
echo "<a id='pagingLink' href='adminControl.php?page=" . $page . "&valueToSearch=". urlencode($_GET['valueToSearch']) ."&search'>" . $page . "</a>";
}
?>
// your code

search not working in pagination

i'm working on a website an i have a page showing all the data from my database with pagination all are working fine except for search.when i search like tom it only shows the result from the first page..i have a name of tom in different pages but it only show result where i'm in the current page.
please help me with this..
class.user.php
<?php
class paginate
{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
public function dataview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php echo $row['user_id']; ?></td>
<td><?php echo $row['username']; ?></td>
<td><?php echo $row['password']; ?></td>
<td><?php echo $row['province']; ?></td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
public function paging($query,$records_per_page)
{
$starting_position=0;
if(isset($_GET["page_no"]))
{
$starting_position=($_GET["page_no"]-1)*$records_per_page;
}
$query2=$query." limit $starting_position,$records_per_page";
return $query2;
}
public function paginglink($query,$records_per_page)
{
$self = $_SERVER['PHP_SELF'];
$stmt = $this->db->prepare($query);
$stmt->execute();
$total_no_of_records = $stmt->rowCount();
if($total_no_of_records > 0)
{
?><tr><td colspan="4" align="center"><?php
$total_no_of_pages=ceil($total_no_of_records/$records_per_page);
$current_page=1;
if(isset($_GET["page_no"]))
{
$current_page=$_GET["page_no"];
}
if($current_page!=1)
{
$previous =$current_page-1;
echo "<a href='".$self."?page_no=1'>First</a> ";
echo "<a href='".$self."?page_no=".$previous."'>Previous</a> ";
}
for($i=1;$i<=$total_no_of_pages;$i++)
{
if($i==$current_page)
{
echo "<strong><a href='".$self."?page_no=".$i."' style='color:red;text-decoration:none'>".$i."</a></strong> ";
}
else
{
echo "<a href='".$self."?page_no=".$i."'>".$i." </a> ";
}
}
if($current_page!=$total_no_of_pages)
{
$next=$current_page+1;
echo "<a href='".$self."?page_no=".$next."'>Next</a> ";
echo "<a href='".$self."?page_no=".$total_no_of_pages."'>Last</a> ";
}
?></td></tr><?php
}
}
}
jquery/ajax
<script>
$(document).ready(function(){
$("#searchme").keyup(function(){
if( $(this).val() != "")
{
$("#data tbody>tr").hide();
$("#data td:contains-ci('" + $(this).val() + "')").parent("tr").show();
}
else
{
$("#data tbody>tr").show();
}
});
});
</script>
index.php
<body>
<div id="table-wrapper" class="table-responsive">
<input type="text" name="search" id="searchme" placeholder="Search...">
<table id="data" class="table table-striped table-hover">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Password</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM login";
$records_per_page=20;
$newquery = $paginate->paging($query,$records_per_page);
$paginate->dataview($newquery);
$paginate->paginglink($query,$records_per_page);
?>
</tbody>
</table>
</div>
</body>

Categories