Pagination not working properly after adding in button for admin - php

I have pagination for a table to display data from the database in the table. This was working fine and I tried to add in a button which only admin's can see. If the user is not an admin they will not see this button. This feature works but once I did it, the pagination only shows one row of data compared to the maximum of 10 per page.
This is my code:
public function dataview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0) // display records if there are records to display
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$poll_id = $row['poll_id'];
$question = $row['question'];
?>
<tr>
<td><?php echo $row['poll_id']; ?></td>
<td><?php echo $row['question']; ?></td>
<td>Open Poll</td>
<td>Results</td>
<?php
$stmt = $this->db->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt->execute(array(':user_id'=>$_SESSION['user_session']));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0){
$admin = $userRow['admin'];
if($admin == 1){
?>
<td>Delete Poll</td>
<?php
?>
</tr>
<?php
}
}
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
and this is the code on the html page which uses the pagination
<table align="center" border="1" width="100%" height="100%" id="data">
<?php
$query = "SELECT * FROM polls";
$records_per_page=10;
$newquery = $paginate->paging($query,$records_per_page);
$paginate->dataview($newquery);
$paginate->paginglink($query,$records_per_page);
?>
</table>

You are reusing variables like $stmt inside the loop that uses it. So do this:
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0) // display records if there are records to display
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$poll_id = $row['poll_id'];
$question = $row['question'];
?>
<tr>
<td><?php echo $row['poll_id']; ?></td>
<td><?php echo $row['question']; ?></td>
<td>Open Poll</td>
<td>Results</td>
<?php
$stmt2 = $this->db->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt2->execute(array(':user_id'=>$_SESSION['user_session']));
$userRow=$stmt2->fetch(PDO::FETCH_ASSOC);
if($stmt2->rowCount() > 0){
$admin = $userRow['admin'];
if($admin == 1){
?>
<td>Delete Poll</td>
<?php
?>
</tr>
<?php
}
}
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
I have replace the $stmt inside the loop by $stmt2.

Related

How to fix between date to date error in php

When I try to Search Between two dates all are working display on reports-details.php but When I try to fresh reload on reports-details.php show this error Warning:
Invalid argument supplied for foreach() in C:\xampp\htdocs\parking
reservation\admin\reports-details.php on line 52
reports.php content is:
<form action="reports-details.php" method="POST">
<label>From Date</label>
<input type="date" name="start_date">
<label>To Date</label>
<input type="date" name="end_date">
<button name="search">Search</button>
</form>
back-end-reports.php
<?php
include 'config.php';
class report extends Connection{
public function managereport(){
if (isset($_POST['search'])) {
$start_date = $_POST['start_date'];
$end_date = $_POST['end_date'];
$sqlselect = "SELECT * FROM tbl_customers WHERE test_date BETWEEN '$start_date' AND '$end_date' ORDER BY test_date";
$result = $this->conn()->query($sqlselect);
$result->execute();
return $result->fetchAll();
}
}
}
$new_vehicle = new report();
$new_vehicle->managereport();
?>
reports-details.php
<?php
include '../back-end/back-end-reports.php';
$result = new report();
$query = $result->managereport();
?>
<?php $id = 1; foreach($query as $row) { ?>
<tbody>
<tr>
<td><?php echo $id; ?></td>
<td><?php echo $row['serial']; ?></td>
<td><?php echo $row['fullname']; ?></td>
<td><?php echo $row['num_plate']; ?></td>
<td>View | <a class="text-dark" href="print.php">Print</a></td>
</tr>
</tbody>
<?php $id++; } ?>
Your issue here is the if statement in your function
if (isset($_POST['search'])) {
When you refresh your page there is no post data so the managereport returns nothing. The value of $query is therefore empty and so you cant iterate over it in the foreach loop.
My suggestion would be that your mangerreport() should return an empty array in the situation where there is no post data i.e
public function managereport(){
if (isset($_POST['search'])) {
$start_date = $_POST['start_date'];
$end_date = $_POST['end_date'];
$sqlselect = "SELECT * FROM tbl_customers WHERE test_date BETWEEN '$start_date' AND '$end_date' ORDER BY test_date";
$result = $this->conn()->query($sqlselect);
$result->execute();
return $result->fetchAll();
} else {
return array();
}
}
<?php $id = 1; foreach($query as $row) { ?>
When using the foreach loop, you must first judge the array $query, otherwise you will be prompted to report an error like this Invalid argument supplied for foreach() , you can add judgment before the loop,
<?php $id = 1; if (is_array($query) && count($query)) {
foreach($query as $row) { ?>
<tbody>
<tr>
<td><?php echo $id; ?></td>
<td><?php echo $row['serial']; ?></td>
<td><?php echo $row['fullname']; ?></td>
<td><?php echo $row['num_plate']; ?></td>
<td>View | <a class="text-dark" href="print.php">Print</a></td>
</tr>
</tbody>
<?php $id++; } } ?>

Delete record in php and mysqli

l have created an application using php,html and mysql. The application can store a user's information such as id, name, bio, and date created into the database and display in html table. The id is an auto increment value which increases with every data entered by the user. The insert part of the application works fine but when l try to delete a record nothing happens. An html form is part of the code which l have intentionally decided not to include. Here is a snapshot of my code:
$records = array();
if(!empty($_POST)) {
if(isset($_POST['firstName'],$_POST['lastName'], $_POST['bio'])){
$firstName = trim($_POST['firstName']);
$lastName = trim($_POST['lastName']);
$bio = trim($_POST['bio']);
if(!empty($firstName) && !empty($lastName) && !empty($bio)) {
$insert = $db->prepare("INSERT INTO people (firstName, lastName,
bio, created) VALUES (?, ?,?, NOW())");
$insert->bind_param('sss', $firstName, $lastName, $bio);
if($insert->execute()){
header('Location: addressbook.php');
die();
}
}
}
}
if($results = $db->query("SELECT * FROM people")){
if($results->num_rows){
while($row = $results->fetch_object()){
$records[] = $row;
}
$results->free();
}
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class = "container">
<?php
if(!count($records)){
echo 'No records found';
}
else{
?>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Bio</th>
<th>Created</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
foreach ($records as $r) {
?>
<tr>
<td><?php echo escape($r->id);?></td>
<td><?php echo escape($r->firstName); ?></td>
<td><?php echo escape($r->lastName); ?></td>
<td><?php echo escape($r->bio); ?></td>
<td><?php echo escape($r->created); ?></td>
<td>
<a onclick="return confirm('Do you want to delete the
record')" href="addressbook.php?idd=<?php echo $row['id'] ?>"
class="btn btn-
danger">Delete</a></td>
<?php
}
?>
</tr>
//My guess is the problem is with this code down here for deleting
<?php
if(isset($_POST['idd'])){
$idd = $_POST['idd'];
$results = $db->query("DELETE FROM people WHERE id=$idd");
if($results){
header('Location: addressbook.php');
}
}
?>
</tbody>
</table>
<?php
}
?>
you need to use $_GET because by default href tag sends the data with GET method.
your code should be
if(isset($_GET['idd'])){
$idd = $_GET['idd'];
$results = $db->query("DELETE FROM people WHERE id='$idd'");
if($results){
header('Location: addressbook.php');
}
}
NOTE- use prepared statement for avoiding sql injection attack
`
<?php
//database connectivity
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"<db_name>");
$idd = $_REQUEST['idd'];
$sql= "DELETE FROM people WHERE id='$idd' ";
$result = mysqli_query($con,$sql) or die(mysql_error());
header("refresh:0.1; addressbook.php");
?>`
if(isset($_GET['idd'])){
$idd = $_GET['idd'];
$results = $db->query("DELETE FROM people WHERE id='{$idd}'");
Try adding a single quote.
If it still doesn't work, please see if the $_POST is actually posting correctly.
Try $results = $db->query("DELETE * FROM people WHERE id=$idd"); instead of $results = $db->query("DELETE FROM people WHERE id=$idd"); in the delete User Function :)

php dynamic pagination logical error

I am developing a page where a user can enter the limit of the table in pagination. While I am doing this the data I enter is taken and query is performed according to that. But as I click on another page of that table the value is reset to default which I set to 5 here.
<?php session_start(); ?>
Submit New record<br><br>
<form method="post">
<input type="text" name="dlimit">
<input type="submit" name="submit">
</form>
<?php
$database = 'test';
require 'connection.php';
if(!isset($_POST['submit']))
{
$limit = 5;
}
else
{
$dlimit = $_POST['dlimit'];
$limit = $dlimit;
}
#$id = $_GET['id'];
if($id==""||$id==null)
{
$page=0;
}
else
{
$page = ($id*$limit)-$limit;
}
$qq ="select * from record limit $page,$limit";
$result = $link -> query($qq);
?>
<table border="1"><th>ID</th>
<th>Name</th>
<th>qualification</th>
<th>address</th>
</tr>
<?php
while ($row = mysqli_fetch_object($result))
{
?>
<tr>
<td><?php echo $row->id ?></td>
<td><?php echo $row->user_name ?></td>
<td><?php echo $row->qualification ?></td>
<td><?php echo $row->address ?></td>
</tr>
<?php
}
?>
</table>
<?php
$query = "SELECT * FROM record";
$result = $link -> query($query);
$rows = mysqli_num_rows($result);
$rr = $rows/$limit;
$rr = ceil($rr);
for ($i=1; $i<=$rr ; $i++) {
?>
<?php echo #$i;?>
<?php
}
mysqli_close($link)
?>
Run the above code and check. If my words are not clear to you.
I think that the $_POST data is missing. You click on the link, so the new page will open without POST infos.
You can change this, if you switch to GET instead of POST. You can add the GET parameter to your <a href=""> Tag.
For example
<a href="pagination.php?page=5&dlimit=100
Also try to avoid the #error suppression and don't pass the $_POST/$_GET Vars directly to your sql string. Bad people could use it for SQL Injections
So I got the answer for my question. I am posting it here if anyone need it on later basis.
Submit New record<br><br>
<form method="get">
<input type="text" name="dlimit">
<input type="submit" name="submit">
</form>
<?php
$database = 'test';
require 'connection.php';
if(empty($_GET['dlimit']) && !isset($_GET['submit']) && empty($_GET['n']))
{
$limit = 5;
global $limit;
}
else
{
if (isset($_GET['dlimit']))
{
$limit = $_GET['dlimit'];
}
else
{
#$limit = $_GET['n'];
}
global $limit;
}
if(!isset($_GET['submit'])&& empty($_GET['n']))
{
$n=5;
global $n;
}
else
{
if(empty($_GET['dlimit']))
{
$n=$_GET['n'];
}
else
{
$n=$_GET['dlimit'];
}
global $n;
}
#$id = $_GET['id'];
if($id==""||$id==null)
{
$page=0;
}
else
{
$page = ($id*$limit)-$limit;
}
$qq ="select * from record limit $page,$limit";
$result = $link -> query($qq);
?>
<table border="1"><th>ID</th>
<th>Name</th>
<th>qualification</th>
<th>address</th>
</tr>
<?php
while ($row = mysqli_fetch_object($result))
{
?>
<tr>
<td><?php echo $row->id ?></td>
<td><?php echo $row->user_name ?></td>
<td><?php echo $row->qualification ?></td>
<td><?php echo $row->address ?></td>
</tr>
<?php
}
?>
</table>
<?php
if (!isset($_GET['submit']) && empty($_GET['n'])) {
$n = 5;
global $n;
}
else
{
if (empty($_GET['dlimit'])) {
$n = $_GET['n'];
}
else
{
$n = $_GET['dlimit'];
}
global $n;
}
$query = "SELECT * FROM record";
$result = $link -> query($query);
$rows = mysqli_num_rows($result);
$rr = $rows/$limit;
$rr = ceil($rr);
for ($i=1; $i<=$rr ; $i++) {
?>
<?php echo #$i;?>
<?php
}
mysqli_close($link)
?>
Again I am mentioning here that files which I included here are just connection where I filled my connection details and other is my record entry file where data is entered by the user.

Filter MySQL Table Search

I am trying to set up a PHP MySQL search script which will let me print the content of my membership MySQL database table and then filter the results using different criteria.
The following fields are used in my MySQL table:
committee_id
rank
last_name
first_name
sex
address
email
phone_number
active_status
I want 2 ways to filter the data:
1) using using a drop down with all the available rank i can filter the results by rank of member.
2) using a drop down with all the available active_status you can filter the results by active status only.
I have set up my search form successfully, and printed all MySQL Table contents, Only the search by position part is filtering my result, but not the active_status, the filter part is a challenge. here is my html table and search script:
<?php include("./includes/connnect.php");?>
<!DOCTYPE HTML>
<html>
<body>
<table>
<thead>
<tr>
<td>ID</td>
<td>position</td>
<td>Last Name</td>
<td>First Name</td>
<td>Sex</td>
<td>Address</td>
<td><strong>Email</td>
<td><strong>Phone Number</td>
<td>Status</td>
</tr>
</thead>
<tbody>
<?php
if ($_REQUEST["position"]<>'') {
$search_position = " AND position='".mysql_real_escape_string($_REQUEST["position"])."'";
}
if ($_REQUEST["status"]<>'') {
$search_status = " AND status='".mysql_real_escape_string($_REQUEST["status"])."'";
}
else {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE committee_id>0".$search_position.$search_status;
}
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)) {
?>
<tr>
<td><?php echo $row["committee_id"]; ?></td>
<td><?php echo $row["rank"]; ?></td>
<td><?php echo $row["last_name"]; ?></td>
<td><?php echo $row["first_name"]; ?></td>
<td><?php echo $row["sex"]; ?></td>
<td><?php echo $row["address"]; ?></td>
<td><?php echo $row["email"]; ?></td>
<td><?php echo $row["phone_number"]; ?></td>
<td><?php echo $row["active_status"]; ?></td>
</tr>
<?php
}
} else {
?>
<tr><td colspan="5">No results found.</td>
<?php
}
?>
</tbody>
</table>
</body>
</html>
I would appreciate any suggestions to get this going.
Thanks.
That is because when there is $_REQUEST["status"] the variable SQL is not setted as you put it on the else statement
if ($_REQUEST["status"]<>'') {
$search_status = " AND status='" .
mysql_real_escape_string($_REQUEST["status"])."'";
}
else { /// this is your problem
$sql = "SELECT * FROM ".$SETTINGS["data_table"]."
WHERE committee_id>0".$search_position . $search_status;
}
Put the $sql out of the else and take the else out.
Thank you Jorge your solution worked. But I got the same result with these elseif statements:
if ($_REQUEST["position"]<>'') {
$search_position = " AND position='".mysql_real_escape_string($_REQUEST["position"])."'";
}
if ($_REQUEST["status"]<>'') {
$search_status = " AND status='".mysql_real_escape_string($_REQUEST["status"])."'";
}
if ($_REQUEST["position"]<>'' and $_REQUEST["status"]<>'') {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]."
WHERE position = '".mysql_real_escape_string($_REQUEST["position"])."'
AND status = '".mysql_real_escape_string($_REQUEST["status"])."'";
}else if ($_REQUEST["position"]<>'') {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE position = '".mysql_real_escape_string($_REQUEST["position"])."'".$search_city;
}else if ($_REQUEST["status"]<>'') {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE status = '".mysql_real_escape_string($_REQUEST["status"])."'".$search_position;
}else {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE committee_id>0".$search_position.$search_status;
}
I shall have to convert these to mysqli or pdo as advised.

How to set my query for a PDO prepared statement

I have built a PDO connection and query, now I need it to be safe from SQL Injection
Here is my code
User Input
<?php $search=$_GET["Search"];?>
SQL that querys DB
<?php
// Issue the query
$Recordset1 = $dbh->query("SELECT * FROM catelogue
WHERE catelogue.TITLE LIKE '$search'");
$Recordset1->setFetchMode(PDO::FETCH_ASSOC);
?>
Fetch The rows
<?php $row_Recordset1 = $Recordset1-> fetch(); ?>
After this there is a table with a do-while loop to display everything that was returned
How do I make a prepared statement for my query?
Thanks
EDIT:
Ok That last bit of code that DavdRew posted helped to get my search working again. Now I have 2 new problems.
Problem 1: After doing a few querys I get this message
mysql_pconnect() [function.mysql-pconnect]: MySQL server has gone away
It still shows the rest of my page with what I searched for. How is this fixed?
Then Problem 2:
With every search the first record returned is empty, a blank record. It never did this before, Why is it doing it now?
Many Thanks DavdRew
EDIT: ADDED MORE CODE
THIS IS THE ENTIRE PDO CODE
<?php
$hostname_EchosPDO = "localhost";
$username_EchosPDO = "echos";
$password_EchosPDO = "echos";
$database_EchosPDO = "full catelogue";
$connStr = 'mysql:host=localhost;dbname=full catelogue';
try {
$dbh = new PDO($connStr, $username_EchosPDO, $password_EchosPDO);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<?php
$q = $dbh->prepare("SELECT * FROM catelogue WHERE catelogue.TITLE LIKE ?"); // prepare statement
if ($q->execute(array('sharpay%'))) // execute wirh passed params array($search)
{
$row_Recordset1 = $q->fetchAll(PDO::FETCH_ASSOC); // store fetched result into $rows;
}
else
{
$error = $dbh->errorInfo();
throw new Exception("SQLSTATE: {$error[0]}. {$error[1]} {$error[2]}");
}
?>
<?php /* $row_Recordset1 = $Recordset1-> fetch(); */ ?>
<?php do { ?>
<table width="800" border="0">
<tr>
<form action="/Echos Online/Detail.php" method="get"><input value='<?php echo $row_Recordset1['CAT NO.']; ?>' name="detail" type="hidden"/><td width='100' rowspan='4'><input type="image" img src="<?php echo $row_Recordset1['IMAGE PATH']; ?>" width="<?php if ($row_Recordset1['FORMAT']=='DVD') {echo "70";} else if ($row_Recordset1['FORMAT']=='DVD+CD') {echo "70";} else if($row_Recordset1['FORMAT']=='BLURAY+CD') {echo "81";}else if($row_Recordset1['FORMAT']=='BLURAY+DVD') {echo "81";} else if($row_Recordset1['FORMAT']=='BLURAY') {echo "81";} else {echo "100";} ?>" height="100"></td></form>
<td width="100">Artist:</td>
<td><?php echo $row_Recordset1['ARTIST']; ?></td>
</tr>
<tr>
<td width="100">Title</td>
<td><?php echo $row_Recordset1['TITLE']; ?></td>
</tr>
<tr>
<td width="100">Format</td>
<td><?php echo $row_Recordset1['FORMAT']; ?></td>
</tr>
<tr>
<td width="100">Cat. No.</td>
<td><?php echo $row_Recordset1['CAT NO.']; ?></td>
</tr>
<hr background-color="#e4a566" color="#e4a566"; width="100%"/>
<?php } while ($row_Recordset1 = $q-> fetch()); ?>
</table>
Honestly now I'm at the piont of going back to preg_replace and mysql_real_escape_string
Thanks for the help
Like this:
$q = $this->pdo->prepare($query);
$data = array();
if ($q->execute($params)) // params is the array of values for each '?' in your prepared statement.
$data = $q->fetchAll($fetch);
else
{
$error = $this->pdo->errorInfo();
throw new \Exception("SQLSTATE: {$error[0]}. {$error[1]} {$error[2]}");
}
return $data;
Keep in mind that WHERE IN works bad, you need to put as much ? into you imploded by , and wrapped with IN ( from left and ) right.
Example:
$statement = $pdo->prepare('SELECT * FROM my_table AS m WHERE m.id = ?');
if ($statement->execute(array(24))) // here you can pass values too.
$data = $q->fetchAll(\PDO::FETCH_ASSOC);
else
exit('Shit happens');
This search for record with id = 24;
For your code, that would be:
$q = $dbh->prepare("SELECT * FROM catelogue WHERE catelogue.TITLE LIKE ?"); // prepare statement
if ($q->execute(array($search))) // execute wirh passed params array($search)
{
$rows = $q->fetchAll(PDO::FETCH_ASSOC); // store fetched result into $rows;
}
else
{
$error = $dbh->errorInfo();
throw new Exception("SQLSTATE: {$error[0]}. {$error[1]} {$error[2]}");
}
Output:
<table width="800" border="0">
<?php foreach ($rows as $row): ?>
<tr>
<form action="/Echos Online/Detail.php" method="get"><input value='<?php echo $row['CAT NO.']; ?>' name="detail" type="hidden"/><td width='100' rowspan='4'><input type="image" img src="<?php echo $row['IMAGE PATH']; ?>" width="<?php if ($row['FORMAT']=='DVD') {echo "70";} else if ($row['FORMAT']=='DVD+CD') {echo "70";} else if($row['FORMAT']=='BLURAY+CD') {echo "81";}else if($row['FORMAT']=='BLURAY+DVD') {echo "81";} else if($row['FORMAT']=='BLURAY') {echo "81";} else {echo "100";} ?>" height="100"></td></form>
<td width="100">Artist:</td>
<td><?php echo $row['ARTIST']; ?></td>
</tr>
<tr>
<td width="100">Title</td>
<td><?php echo $row['TITLE']; ?></td>
</tr>
<tr>
<td width="100">Format</td>
<td><?php echo $row['FORMAT']; ?></td>
</tr>
<tr>
<td width="100">Cat. No.</td>
<td><?php echo $row['CAT NO.']; ?></td>
</tr>
<hr background-color="#e4a566" color="#e4a566"; width="100%"/>
<?php endforeach; ?>
</table>
$pdo = new PDO('mysql:host=localhost;dbname=mydb', $username, $password);
$stmt = $pdo->prepare('SELECT * FROM catelogue WHERE catelogue.TITLE LIKE :search');
$stmt->bindValue('search', $search);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
OR
$stmt = $pdo->prepare('SELECT * FROM catelogue WHERE catelogue.TITLE LIKE :search');
$stmt->execute(array('search' => $search);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
note that you probably want to have your $search string wrapped with wildcard characters, like
$stmt->bindValue('search', '%'.$search.'%');
also note that searching using like wont use index if you have wildcard on left side of like criteria
$stmt->bindValue('search', '%'.$search.'%'); //will not use index
$stmt->bindValue('search', $search.'%'); //will use index

Categories