pagination using php pdo mysql - php

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");

Related

PHP MySQL update multiple row with check box

I want to update checked values in MySQL with PHP
<?php
require "../../../../config.php";
if (isset($_POST['btn-upload'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$status = $_POST['status'];
$ck_id = $_POST['ck_id'];
for ($i = 0; $i < sizeof($ck_id); $i++) {
$sql = "UPDATE form_eg208 SET status=:status where ck_id IN (:ck_id)";
$statement = $connection->prepare($sql);
$statement->bindParam(':status', $status[$i]);
$statement->bindParam(':ck_id', $ck_id[$i]);
$statement->execute();
}
} catch (PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
if ($statement->rowcount() >= 0) {
echo '<div class="alert alert-success alert-dismissible" id="flash-
msg">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×
</a>
<h4> <strong>Success!</strong> Insert Record
Successfully</h4>
</div>';
} else {
echo '<div class="alert alert-danger alert-dismissible" id="flash-
msg">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×
</a>
<h4> <strong>Failed!</strong> Duplicate BGLPARTNO</h4>
</div>';
}
}
?>
my html code is
<?php
$id = $_REQUEST['cid'];
try {
$connection = new PDO($dsn, $username, $password, $options);
$j = 1;
$sql = "CALL view_eg208 (:bglpartno)";
$statement = $connection->prepare($sql);
$statement->bindParam(':bglpartno', $id);
$statement->execute();
$result = $statement->fetchAll();
} catch (PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
foreach ($result as $row1)
?>
<div class="container-fluid">
<div class="row">
<div class="col-md-12" style="margin-top:40px;">
<div class="card">
<div class="card-body">
<form method="post" action="" enctype='multipart/form-data' class="needs-validation" novalidate>
<div class="table-responsive m-t-40">
<table id="myTable" class="table table-hover table-bordered">
<thead class="thead-dark">
<tr>
<th>No.</th>
<th>Activity</th>
<th style="text-align:center;">Status</th>
</tr>
</thead>
<tbody>
<?php
if ($result && $statement->rowCount() > 0) {
foreach ($result as $row) { ?>
<tr>
<td>
<input type="checkbox" id="ck_id[]" class="filled-in chk-col-blue"
name="ck_id[]" value="<?php echo escape($row["ck_id"]); ?>"/>
</td>
<td style="color:black"><?php echo escape
($row["activity_name"]); ?></td>
<td>
<div class="form-group has-danger"
style="margin-bottom: 0;">
<input type="text" id="status[]" name="status[]" maxlength="100" class="form-control" value="<?php echo escape($row["status"]);?>" autocomplete="off" required="required">
<div class="invalid-feedback">
Please provide a Inputs.
</div>
</div>
</td>
</tr>
<?php }
}
$connection = null;
?>
</tbody>
</table>
When I update all the values then it works correctly but when single value then it updates the value of first box into that box which I selected. Please help me to solve this
Please make your checkbox input like this so you get the right status for the right ck_id index :
if ($result && $statement->rowCount() > 0) {
foreach ($result as $i => $row) { ?>
<tr>
<td>
<input type="checkbox" id="ck_id[]"class="filled-in chk-col-blue"
name="ck_id[<?php echo $i ?>]" value="<?php echo escape ($row["ck_id"]);?>"/>
</td>
<td style="color:black"><?php echo escape
($row["activity_name"]);?></td>
<td>
<div class="form-group has-danger"
style="margin-bottom: 0;">
<input type="text" id="status[]" name="status[<?php echo $i ?>]"
maxlength="100" class="form-control" value="<?
php echo escape ($row["status"]);?>" autocomplete="off"
required="required" >
<div class="invalid-feedback">
Please provide a Inputs.
</div>
</div>
</td>
</tr>
<?php
}
}
Also try to use foreach instead of for loops :
try {
$connection = new PDO($dsn, $username, $password, $options);
$status = $_POST['status'];
$ck_id = $_POST['ck_id'];
// for ($i = 0; $i < sizeof($ck_id); $i++) {
foreach ($ck_id as $i => $value) {
$sql = "UPDATE form_eg208 SET status=:status where ck_id IN (:ck_id)";
$statement = $connection->prepare($sql);
$statement->bindParam(':status', $status[$i]);
$statement->bindParam(':ck_id', $ck_id[$i]);
$statement->execute();
}
} catch (PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}

How to search with PHP/MySQL using Pagination

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?

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?

Fix Table Output for PHP

I am trying to make a table in PHP.
There is form where I am taking in Value - Market, Production Date, Sales Date and sending it in POST to Table to get it populated.
At the POST I am calling a set of data from production table from MySQL and populating in the same table.
I am able to populate the table from SQL and Form POST Action but I am not able to align them as per the required output format.
Please help in finding fix for the below Code:
<?php
if(isset($_POST['for_post']))
{
try
{
?>
<div class="card-box" style="padding-left:5px;padding:10px;padding-bottom:50px">
<div class="row">
<div class="col-sm-12">
<?php
if(isset($_POST['for_post_market'])){ $pname = $_POST['for_post_market']; }
if(isset($_POST['for_post_prod_date'])){ $pcat = $_POST['for_post_prod_date']; }
if(isset($_POST['for_post_sale_date'])){ $pprice = $_POST['for_post_sale_date']; }
$query = 'SELECT * FROM product';
$stmt = $DB_con->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$row['prod_cat_name']][] = $row['prod_name'];
}
?>
<table id="invoices" border="1">
<thead>
<th>Category</th>
<th>Product</th>
<th>Production Date</th>
<th>Sales Date</th>
<th>Market</th>
</thead>
<tbody>
<?php
foreach($result as $id => $invoices) {
echo '<tr>';
echo '<td rowspan='. count($invoices) . '>' . $id . '</td>';
$count = 0;
foreach ($invoices as $invoice) {
if ($count != 0) {
echo '<tr>';
}
echo "<td>$invoice</td>";
echo "<td>".$pcat."</td>";
echo "<td>".$pprice."</td>";
$count++;
}
}
$a=count($pname);
for($i=0;$i<$a;$i++)
{
echo "<td>".$pname[$i]."</td></tr>";
}
echo "</tbody>";
echo "</table>";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{ ?>
</div>
</div>
</div>
<div class="card-box" style="padding-left:5px;padding:10px;padding-bottom:50px">
<div class="row">
<div class="col-sm-12">
<form class="form-inline" method="post">
<div class="form-group m-r-10">
<label for="exampleInputName2">Market : </label>
<div class="input-group">
<select class="selectpicker" multiple data-selected-text-format="count" data-style="btn-white" name="for_post_market[]">
<?php
$stmt = $DB_con->prepare('Select * from location');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['location_name'].'</option>';
}
?>
</select>
<div>
&nbsp
<div class="form-group m-r-10">
<label for="exampleInputEmail2">Production Date : </label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclose" name="for_post_prod_date">
<span class="input-group-addon bg-custom b-0 text-white"><i class="icon-calender"></i></span>
</div>
</div>
<div class="form-group m-r-10">
<label for="exampleInputEmail2">Sales Date : </label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker2-autoclose" name="for_post_sale_date">
<span class="input-group-addon bg-custom b-0 text-white"><i class="icon-calender"></i></span>
</div>
</div>
<button type="submit" class="btn btn-default waves-effect waves-light btn-md" id="for_post" name="for_post">
Submit
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
}
?>
The Current Output that I am able to get from this code is :
What I am trying to get is :
Updated Changes Suggested and worked:
<table id="invoices" border="1">
<thead>
<th>Category</th>
<th>Product</th>
<th>Production Date</th>
<th>Sales Date</th>
<th>Market</th>
<th>Input</th>
</thead>
<tbody>
<?php
$a=count($pname);
foreach($result as $id => $invoices) {
echo '<tr>';
echo '<td rowspan='. count($invoices)*$a . '>' . $id . '</td>';
$count = 0;
foreach ($invoices as $invoice) {
if ($count != 0) {
echo '<tr>';
}
echo '<td rowspan='. count($pname) . '>' . $invoice . '</td>';
echo '<td rowspan='. count($pname) . '>' . $pcat . '</td>';
echo '<td rowspan='. count($pname) . '>' . $pprice . '</td>';
for($i=0;$i<$a;$i++)
{
echo '<td>'. $pname[$i] . '</td>';
echo '<td><input type="text" class="form-control"></td></tr>';
}
$count++;
}
}
echo '</tbody>';
echo '</table>';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{ ?>
You have to set Category column rowspan to count($invoices)*count($pname) and set rowspan to Product, Production date and Sales date columns to count($pname)

disable or remove 'next' button when there aren't anymore records to display PHP

I have a simple php page which has records displaying in a table. I have successfully managed to add some sort of pagination to the page however I am confused about how to disable or not show the 'next' button if there aren't anymore records to display. Right now it will just allow the user to keep clicking 'next' and display an empty table. Can anybody help me achieve this?
This is the code I have at the moment:
<?php
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//give the value of the starting row to 0
$startrow = 0;
//otherwise 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 course_details LIMIT $startrow, 5");
$stmt->execute();
$courses = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch(Exception $e)
{
die ("Could not connect to the database $mysql_dbname :" . $e->getMessage());
}
?>
<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">
Course Code
</th>
<th class="text-center">
Course Title
</th>
</tr>
</thead>
<tbody>
<!-- populating the table with information from mysql database -->
<?php foreach ($courses as $row) {
echo "<tr><td>";
echo $row['course_code'];
echo "</td><td>";
echo $row['course_title'];
echo "</td><td>";
echo "</tr>"; }
?>
</tbody>
</table>
<?PHP
echo 'Next';
$prev = $startrow - 5;
if ($prev >= 0)
echo 'Previous';
?>
</div>
</div>
Which looks like this when there are records:
And this when there aren't any:
Thanks in advance!
You could count the number of displayed records. If it is less than 5 there is certainly no more records to show.
<?php
$recordCount = 0;
foreach ($courses as $row) {
$recordCount++;
echo "<tr><td>";
...
}
?>
echo a "Next" with no link if $recordCount < 5
echo $recordCount == 5
? 'Next';
: '<span class="pull-right">Next</span>';
Before echoing the Next button, execute another query for the next record using
LIMIT $startrow+5, 1
Then
if (count($courses) > 0)
echo next button

Categories