How to search with PHP/MySQL using Pagination - php

I wrote this code:
<div class="container mx-auto">
<!--Add class table-responsive for responsive table -->
<div class="row">
<div class="col-md-6">
<form method="post">
<div class="input-group">
<input size='14' type="text" class="form-control" placeholder="Search for..." name="searchValue">
<span class="input-group-btn">
<button class="btn btn-secondary" name='search' type="submit"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
</div>
</div>
<table class="table mx-auto" id="'table">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Email</th>
<th>Phone</th>
<th>Company</th>
<th>More</th>
</tr>
</thead>
<tbody>
<?php
$pagination = new Pagination(7);
$page_max = $pagination->getPageMax();
$start = $pagination->getStart();
if(!isset($_POST['search'])) {
$numberOfPages = $pagination->numberOfPages($database->getData("SELECT count(id) FROM customers"));
$customers = $database->getDataAsArray("SELECT * FROM customers LIMIT $start, $page_max");
}
else{
$searchValue = '%'. $_POST['searchValue'] . '%';
$numberOfPages = $pagination->numberOfPages($database->getData("SELECT count(id) FROM customers WHERE name LIKE '$searchValue' "));
$customers = $database->getDataAsArray("SELECT * FROM customers WHERE name LIKE '$searchValue' LIMIT $start, $page_max");
}
foreach($customers as $customer){
$name = $customer ['name'];
$surname = $customer['surname'];
$email = $customer['email'];
$phone = $customer['phone'];
$company = $customer['company'];
$id = $customer['id'];
echo "<tr>
<td>$name</td>
<td>$surname</td>
<td>$email</td>
<td>$phone</td>
<td>$company</td>
<td><a href='customerInfo.php?id=$id' class='btn btn-sm btn-info'><i class='fa fa-info'></i></a></td>
</tr>";
}
?>
</tbody>
</table>
<ul class="pagination">
<?php
echo $pagination->previous($numberOfPages);
for($i = 0; $i < $numberOfPages; $i++){
echo '<li class="page-item"><a class="page-link" href="?page='. $i . '">'. $i. '</a></li>';
}
echo $pagination->next($numberOfPages);
?>
</ul>
</div>
The getDataAsArray function is like this:
public function getDataAsArray($myQuery){
$this->connection = mysqli_connect($this->host, $this->dbUsername, $this->dbPassword, 'portal');
$query = mysqli_query($this->connection, $myQuery);
$results = array();
while($line = mysqli_fetch_array($query)){
$results[] = $line;
}
return $results;
}
I know I should use :[name] or something to set a parameter in my query,the question is not about that and ofcourse I should use a prepared statment. Will do that later.
The question:
I wrote the code to search in the db records. I works fine but when I search it creates a new pagination with all the new records and when I click on the second page. The page builds the pagination with all the records from the database so I won't use it's searchValue anymore.
I think this issue will be solved with a $_GET parameter like search in the URL or Ajax but I don't know how.
Could anyone help me out?

Related

Codeigniter Pagination directs me to 'about:blank#blocked'

Codeigniter Pagination doesnt work, the URL changes to 'about:blank#blocked'.
I'm fairly new at php frameworks and codeigniter. I tried to read the documentation but I don't seem to see the problem.
Controller:
class Listing extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
//Get Total Records Count
$this->db->select("*");
$this->db->from("cities");
if (!empty($_GET['cityFilter'])) {
$this->db->like('city_name', $_GET['cityFilter']);
}
$cityRecordsCount = $this->db->get();
$totalRecords = $cityRecordsCount->num_rows();
$limit = 10;
if (!empty($_GET['cityFilter'])) {
$config["base_url"] = base_url('Listing/index?cityFilter=' . $_GET['cityFilter']);
} else {
$config["base_url"] = base_url('Listing/index?cityFilter=');
}
$config["total_rows"] = $totalRecords;
$config["per_page"] = $limit;
$config['use_page_numbers'] = TRUE;
$config['page_query_string'] = TRUE;
$config['enable_query_strings'] = TRUE;
$config['num_links'] = 2;
$config['cur_tag_open'] = ' <li class="active"><a>';
$config['cur_tag_close'] = '</a></li>';
$config['next_link'] = 'Next';
$config['prev_link'] = 'Previous';
$this->pagination->initialize($config);
$str_links = $this->pagination->create_links();
$links = explode(' ', $str_links);
$offset = 0;
if (!empty($_GET['per_page'])) {
$pageNo = $_GET['per_page'];
$offset = ($pageNo - 1) * $limit;
}
//Get actual result from all records with pagination
$this->db->select("*");
$this->db->from("cities");
if (!empty($_GET['cityFilter'])) {
$this->db->like('city_name', $_GET['cityFilter']);
}
$this->db->limit($limit, $offset);
$cityRecords = $this->db->get();
$this->load->view('listCities', array(
'totalResult' => $totalRecords,
'results' => $cityRecords->result(),
'links' => $links
));
}
}
HTML
<div id="container">
<div class="row">
<div class="col-md-8 col-md-offset-2 col-lg-8 col-lg-offset-2 col-sm-12">
<h1>Pagination With Search.</h1>
<p>A demo for Codeigniter 2.X framework</p>
<br>
<form action="" method="GET">
<div class="input-group pull-right">
<input type="text" class="form-control" placeholder="Search For City"
name="cityFilter" value="<?php
if (!empty($_GET['cityFilter'])) {
echo $_GET['cityFilter'];
}
?>">
<span class="input-group-btn">
<button type="submit" class="btn btn-success"><i class="fa fa-search"></i> Search</button>
</span>
</div>
</form>
<table class="table table-bordered table-hover" border="1">
<thead>
<tr>
<th>#</th>
<th>City Name</th>
<th>City State</th>
</tr>
</thead>
<tbody>
<?php
foreach ($results as $o) {
?>
<tr>
<td><?php echo $o->city_id; ?></td>
<td><?php echo $o->city_name; ?></td>
<td><?php echo $o->city_state; ?></td>
</tr>
<?php }
?>
</tbody>
<tfoot>
</tfoot>
</table>
<ul class="pagination pull-right">
<!-- Show pagination links -->
<?php
foreach ($links as $link) {
echo "<li>" . $link . "</li>";
}
?>
</ul>
</div>
</div>
</div>
It shows a blank page and the URL changes to 'about:blank#blocked'. What am I doing wrong?

multiple checkboxes with paging in php without using javascript and jquery

Good day, I have an HTML table and I use paging on it so that only a certain amount of items is shown. The problem is that I need to have multiple selections with checkboxes and that works for a single page but I need that to work between pages. So for example on page 1 you choose 3 items and in the next page you choose 5 items and when GET happens I need to have all those items in one place so that I can store them in a variable.
<?php
include("connect.php"); //database connection file
$limit = 7;
if ( isset($_GET['page']) ) {
$page_no = $_GET['page'];
} else {
$page_no = 1;
}
$start_from = ($page_no-1)*$limit;
$sql = "SELECT * FROM emp_info LIMIT $start_from,$limit ";
$result = mysqli_query($conn , $sql);
?>
<form method="GET" action="project.php?name=<?php echo
$data['name']; ?>">
<div class="container">
<h2>employee information:</h2>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>EmpId</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php
$info = "SELECT * FROM emp_info LIMIT $start_from,$limit ";
//query to select the data from database
$query = mysqli_query ($conn , $info);
while ( $data = mysqli_fetch_assoc ($query) )
{ //query to fetch the data
$_SESSION['emp_name']=$data['name'];
?> <tr>
<td><?php echo $data['emp_id'];?></td>
<td>
<a href="project.php?id=<?php echo $data['emp_id'];?>&name=<?php echo $data['name']; ?>">
<input type="checkbox" name="check_list[]" value="<?php echo $data['name'];?>">
</a> <?php echo $data['name'];?>
</td>
<td><?php echo $data['email'];?></td>
</tr>
<?php }
?>
</tbody>
</table>
<ul class="pagination">
<?php
$sql = "SELECT COUNT(*) FROM emp_info";
$result = mysqli_query($conn , $sql);
$row = mysqli_fetch_row($result);
$total_records = $row[0];
// Number of pages required.
$total_pages = ceil($total_records /
$limit);
$pagLink = "";
for ( $i = 1; $i <= $total_pages; $i++) {
if ( $i == $page_no) {
$pagLink .= "<p>Pages:</p><li class='active'><a href='datatable.php?id=" . $data['emp_id'] .
"&page=" . $i ."'>". $i ."</a></li>";
} else {
$pagLink .= "<li><a href='datatable.php?page=". $i ."'>". $i ."</a></li>";
}
};
echo $pagLink;
?>
</ul>
</div>
<button type="submit" formaction="project.php"
name="select_proj">Select Project</button>
<button type="submit"
formaction="addnewproj.php" name="add_proj">Add New
Project</button>
</form>
</body>
</html>
I recommend reseaching abit of Javascript and more specificly aJax to solve this issue.
You need somewhere to store the information that has been selected in order to use it somewhere else.

How to create search function in PHP/MySQL

I wrote this code:
<div class="container mx-auto">
<!--Add class table-responsive for responsive table -->
<div class="row">
<div class="col-md-6">
<form method="post">
<div class="input-group">
<input size='14' type="text" class="form-control" placeholder="Search for..." name="searchValue">
<span class="input-group-btn">
<button class="btn btn-secondary" name='search' type="submit"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
</div>
</div>
<table class="table mx-auto" id="'table">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Email</th>
<th>Phone</th>
<th>Company</th>
<th>More</th>
</tr>
</thead>
<tbody>
<?php
$pagination = new Pagination(7);
$page_max = $pagination->getPageMax();
$start = $pagination->getStart();
if(!isset($_POST['search'])) {
$numberOfPages = $pagination->numberOfPages($database->getData("SELECT count(id) FROM customers"));
$customers = $database->getDataAsArray("SELECT * FROM customers LIMIT $start, $page_max");
}
else{
$searchValue = '%'. $_POST['searchValue'] . '%';
$numberOfPages = $pagination->numberOfPages($database->getData("SELECT count(id) FROM customers WHERE name LIKE '$searchValue' "));
$customers = $database->getDataAsArray("SELECT * FROM customers WHERE name LIKE '$searchValue' LIMIT $start, $page_max");
}
foreach($customers as $customer){
$name = $customer ['name'];
$surname = $customer['surname'];
$email = $customer['email'];
$phone = $customer['phone'];
$company = $customer['company'];
$id = $customer['id'];
echo "<tr>
<td>$name</td>
<td>$surname</td>
<td>$email</td>
<td>$phone</td>
<td>$company</td>
<td><a href='customerInfo.php?id=$id' class='btn btn-sm btn-info'><i class='fa fa-info'></i></a></td>
</tr>";
}
?>
</tbody>
</table>
<ul class="pagination">
<?php
echo $pagination->previous($numberOfPages);
for($i = 0; $i < $numberOfPages; $i++){
echo '<li class="page-item"><a class="page-link" href="?page='. $i . '">'. $i. '</a></li>';
}
echo $pagination->next($numberOfPages);
?>
</ul>
</div>
I want to search in my table, this works fine so far but when I search on A for example and I click my pagination page 1 it rebuilds the page with all te records from the database.
I tried to add a parameter to the url upon button click but upon creating this button with link the searchValue is still null.
This question is not about my sql query. It's about searching with pagination
Could anyone help me fix this?

why multiple data doesn't insert in this code

I have a tbl_employee table and tbl_time table, I want to insert multiple data insert for attendance but when I click submit button it's insert only single data . but where is the problem ,help me to find out this..this is insert code
require './db_connect.php';
class Time extends Db_connect {
protected $link;
public function __construct() {
$this->link = $this->database_connection();
}
public function attendance_insert($data) {
extract($data);
$cur_date = date('Y-m-d');
foreach ($time_attendance as $attn_key => $attn_value) {
if ($attn_value == 'P') {
$SQL = "INSERT INTO tbl_time(employee_id,time_date,time_attendance)VALUES('$attn_key','$cur_date','P')";
$atten_date=mysqli_query($this->link, $SQL);
} else if ($attn_value == 'A') {
$SQL = "INSERT INTO tbl_time(employee_id,time_date,time_attendance)VALUES('$attn_key','$cur_date','A')";
$atten_date=mysqli_query($this->link, $SQL);
}
if ($atten_date) {
$massage = "<div class='alert alert-success text-center'><h5>Attendance insert successfully</h5></div>";
return $massage;
} else {
die('Attendance insert query problem' . mysqli_error($this->link));
}
}
}
}
this is html code
<?php
require_once './time.php';
$obj_time = new Time()
$massage = '';
if (isset($_POST['btn'])) {
$massage = $obj_time->attendance_insert($_POST);
}
$employee_view = $obj_employee->employee_all_view();
?>
<div class="container-fluid">
<div class="row">
<center>
<span style="font-size:1.8em;">Attendance form</span>
</center>
</div>
</div>
<hr/>
<?php echo $massage; ?>
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-body panel-default">
<div class="well text-center" style="font-size:15px;">
<strong>Date :</strong>
<?php $current_date = date('Y-M-d');
echo $current_date; ?>
</div>
<form class="form-horizontal" method="post">
<table class="table table-striped table-responsive text-center">
<tr>
<td><b>Serial</b></td>
<td><b>Name</b></td>
<td><b>ID</b></td>
<td><b>Attendance</b></td>
</tr>
<?php
$i = 0;
while ($employee_info = mysqli_fetch_assoc($employee_view)) {
extract($employee_info);
$i++;
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $employee_first_name . ' ' . $employee_last_name; ?></td>
<td><?php echo $employee_id; ?></td>
<td>
<input type="radio" name="time_attendance[<?php echo $employee_id; ?>]" value="P">P
<input type="radio" name="time_attendance[<?php echo $employee_id; ?>]" value="A">A
</td>
</tr>
<?php } ?>
<tr>
<td colspan="4">
<input type="submit" class="btn btn-primary btn-block" name="btn" value="submit"/>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
This :
foreach($time_attendance as $attn_key => $attn_value){
$SQL = "INSERT INTO tbl_time(employee_id,time_date,time_attendance)
VALUES('$attn_key','$cur_date','A')";
$atten_date = mysqli_query($this->link, $SQL);
if ($atten_date) {
$massage = "<div class=''><h5>Attendance insert successfully</h5></div>";
return $massage;
}
}
Literally ask to break the foreach with return $massage; if you query succeed... So yes, you'll only have one record.
Put your return outside the foreach.

pagination using php pdo mysql

I have attempted to set up pagination for a simple database table which selected everything from the database table and displays it in a table for the user however i have been having issues with this. I followed a tutorial which shows how to set up the pagination but i keep encountering a SQLSTATE[42000]: Syntax error or access violation: 1327 Undeclared variable: $startrow error and I'm not sure why.
this is the code:
<?php
include "db_conx.php";
//check if the starting row variable was passed in the URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
try {
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db_conx->prepare('SELECT * FROM role_type LIMIT $startrow, 3');
$stmt->execute();
$roles = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch(Exception $e)
{
die ("Could not connect to the database $mysql_dbname :" . $e->getMessage());
}
?>
<h4><center>Manage Role Types</center></h4>
<div class="container">
<div class = "container-fluid">
<div id = "table_container" style="width:auto; margin-top:50px;" class="mainbox col-md-6">
<div class="row clearfix">
<div class="col-md-12">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
Role Type Code
</th>
<th class="text-center">
Role Title
</th>
</tr>
</thead>
<tbody>
<!-- populating the table with information from mysql database -->
<?php foreach ($roles as $row) {
echo "<tr><td>";
echo $row['role_type_code'];
echo "</td><td>";
echo $row['role_title'];
echo "</td><td>";
echo '<p data-placement="top"
data-toggle="tooltip"
style="margin-left:5px"
title="Edit">';
echo '<button class="btn btn-primary btn-xs"
data-title="Edit"
data-toggle="modal"
data-id="';
echo $row['role_type_code'];
echo '" data-role="';
echo $row['role_title'];
echo '" data-target="#editModal">';
echo '<span class="glyphicon glyphicon-edit" />';
echo '</button></p>';
echo "</td>";
echo "</td><td>";
echo '<p data-placement="top"
data-toggle="tooltip"
style="margin-left:5px"
title="Delete">';
echo '<button class="btn btn-danger btn-xs"
data-title="Delete"
data-toggle="modal"
data-id="';
echo $row['role_type_code'];
echo '" data-role="';
echo $row['role_title'];
echo '" data-target="#deleteModal">';
echo '<span class="glyphicon glyphicon-trash" />';
echo '</button></p>';
echo "</tr>"; }
?>
</tbody>
</table>
<?PHP
//now this is the link..
echo 'Next';
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo 'Previous';
?>
</div>
</div>
no idea why. I've tried using a value in place of the variable but it doesn't work. Any body know how i can overcome this please.
thank you
You can NOT embed php variable in SINGLE quoted strings http://php.net/language.types.string
So your query is wrong
$stmt = $db_conx->prepare('SELECT * FROM role_type LIMIT $startrow, 3');
It needs to be
$stmt = $db_conx->prepare("SELECT * FROM role_type LIMIT $startrow, 3");

Categories