How to change this code from mysqli to PDO - php

if (isset($_GET['page_no']) && $_GET['page_no']!="") {
$page_no = $_GET['page_no'];
} else {
$page_no = 1;
}
$total_records_per_page = 9;
$offset = ($page_no-1) * $total_records_per_page;
$previous_page = $page_no - 1;
$next_page = $page_no + 1;
$adjacents = "2";
$result_count = mysqli_query($con,"SELECT COUNT(*) As total_records FROM `products`");
$total_records = mysqli_fetch_array($result_count);
$total_records = $total_records['total_records'];
$total_no_of_pages = ceil($total_records / $total_records_per_page);
$second_last = $total_no_of_pages - 1; // total page minus 1
$result = mysqli_query($con,"SELECT * FROM `products` LIMIT $offset, $total_records_per_page");
while($row = mysqli_fetch_array($result)){
echo "<tr>
<td>".$row['productCode']."</td>
<td>".$row['productName']."</td>
<td>".$row['MSRP']."</td>
<td><button type='submit' class='buy'>Buy Now</button></td>
</tr>";
}
mysqli_close($con);
?>
I need to change this code to PDO format. And I am not really sure what is the same function of mysqli_fetch_array in PDO.

This is how you would do it:
// Execute query and fetch a single cell from the result
$total_records = $PDO->query('SELECT COUNT(*) FROM `products`')->fetch(PDO::FETCH_COLUMN);
$total_no_of_pages = ceil($total_records / $total_records_per_page);
$second_last = $total_no_of_pages - 1; // total page minus 1
// prepare a statement with 2 parameters and execute it
$stmt = $PDO->prepare('SELECT * FROM `products` LIMIT ?,?');
$stmt->execute([$offset, $total_records_per_page]);
// PDO results are easily traversable
foreach ($stmt->fetchAll() as $row) {
echo "<tr>
<td>".$row['productCode']."</td>
<td>".$row['productName']."</td>
<td>".$row['MSRP']."</td>
<td><button type='submit' class='buy'>Buy Now</button></td>
</tr>";
}
I replaced your concatenated query with a prepared statement, which you should always do!
About fetching: You can traverse the records one by one or fetch all of them like I did into an array and foreach on them. There is many different ways to do it. Always remember about many PDO fetch options available: https://phpdelusions.net/pdo#fetchall

Related

how to get count(*) the right way in php

I tried to count() the data from database with php but it don't show me the total data but it show the datas.
this is how I count
$query = "SELECT
mitra.*,
user.username,
user.privilege,
user.name
FROM
mitra
INNER JOIN
user ON mitra.id_user = user.id "
$result = $connection->query($query);
if ($result->num_rows > 0) {
foreach ($result as $row) :
$id = "" . $row["id"] . "";
$total = "" . $row["total_puas"] . "";
$privilege = "" . $row["privilege"] . "";
if ($privilege == 2) :
$calculate = $total / count($id);
var_dump(count($id));
endif;
endforeach;
}
===================
= id = total =
= 1 = 45.84 =
= 2 = 75.45 =
= 3 = 34.54 =
===================
when I var_dumb it it shows int(1)int(1)int(1) not int(3) that what I wanted.
actually I want to count $calculate with the data in $total that should be there is float and the amount from $total that I want to divided with count id
is there any solution that how to count the amount from $total and can be devided with count $id that should be 3?. please help
what I really trying to do from that table example is like 45.84 + 75.45 + 34.54 / 3
Sounds like you want a COUNT() with GROUP BY in your query. Doing count($id) in PHP will always yield one, as its not an array of values.
$query = "SELECT COUNT(id) as cnt, id, total_puas
FROM table
GROUP BY id";
$result = $connection->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$calculate = $row["total_puas"] / $row['cnt'];
echo $row['id']." has a count of ".$row['cnt'].", a total of ".$row['total_puas']." and calculated to ".$calculate."<br />\n";
}
}
From your updated question, the output becomes a bit more clear. Based on the output data and the result you desire, you want to calculate the sum of all total_paus, divided by the number of rows. You can do this directly in one query, like this
$query = "SELECT SUM(total_puas) / COUNT(u.id) as total
FROM mitra AS m
INNER JOIN user AS u
ON mitra.id_user = user.id";
$result = $connection->query($query);
$row = $result->fetch_assoc();
$total = $row['total'];
echo $total;
You can try this code:
<?php
$i = 0;
$total =0.00;
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()):
if ($row["privilege"] == 2) :
$total = $total + $row["total"];
$i++;
endif;
endwhile;
echo $total."<br>";
echo $i."<br>";
echo $calculate = $total / $i;
}
?>
output
=====================================
$total = 155.83;
$i = 3;
$calculate = $total/$i;
$ans = 51.943333333333;
=====================================
You can try this code:
$query = "SELECT * FROM table"
$result = $connection->query($query);
if ($result->num_rows > 0) {
$total = 0.0;
foreach ($result as $row) :
$id = "" . $row["id"] . "";
$total = $total + $row['total'];
endforeach;
$calculate = $total / $result->num_rows;
echo $total.<br>;
echo $calclulate;
}

php mysqli table pagination

I'm trying to create a pagination for our status table but the records being displayed is not on par with the records that I want to display. Here's my code:
<?php
$query = mysqli_query($connect,"SELECT * FROM inventory_item ") or die ("Error: Could not fetch rows!");
$count = 0;
if (isset($_GET['page_no']) && $_GET['page_no']!="") {
$page_no = $_GET['page_no'];
} else {
$page_no = 1;
}
$total_records_per_page = 3;
$offset = ($page_no-1) * $total_records_per_page;
$previous_page = $page_no - 1;
$next_page = $page_no + 1;
$adjacents = "2";
$query_count = mysqli_query($connect,"SELECT COUNT(*) As total_records FROM `inventory_item`");
$total_records = mysqli_fetch_array($query_count);
$total_records = $total_records['total_records'];
$total_no_of_pages = ceil($total_records / $total_records_per_page);
$second_last = $total_no_of_pages - 1;
$result = mysqli_query($connect,"SELECT * FROM `inventory_item` LIMIT $offset, $total_records_per_page");
while ($row = mysqli_fetch_array($query))
{
$item_name = $row ['item_name'];
echo '<tr><td>'.$row['item_name']. '</td><td>'.$row['description']. '</td><td>'.$row['unit'].'</td>
<td>'.$row['quantity']. '</td><td>'.$row['price']. '</td>
<td>'.$row['price'] * $row['quantity'].'</td>
<td>'.$row['status'].'</td>
<td><a href="inventory_statusEditRecordsFinal1.php?CO='.$item_name.'" title="Click to edit records" class="buttonn"/> Edit </a></td>
<td><a href="inventory_deletestatusFinal.php?item_name='.$item_name.'" title="Click to delete records" class="delbutton" onclick="return ConfirmDelete()"/> Delete </a></td>
</tr>';
}
mysqli_close($connect);
?>
Here's the result, I wanted to display 3 records per page but it displays all the data.

Detect Previous Next ID

I have a little script that have a Previous & Next button.
My problem is I want to detect & place the ID in those buttons
this is the code from the pagination
<body>
<?php include_once 'data.php'; ?>
<center>
<ul class="pagination">
<?php
if($page_counter == 0){
echo "<li><a href=?start='0' class='active'>0</a></li>";
for($j=1; $j < $paginations; $j++) {
echo "";
}
}else{
echo "<a href=?start=$previous><button>Previous</button></a>";
for($j=0; $j < $paginations; $j++) {
if($j == $page_counter) {
echo " ";
}else{
echo " ";
}
}if($j != $page_counter+1)
echo "<a href=?start=$next><button>Next</button></a>";
}
?>
</ul>
</center>
In this part I have the ID but the problem is I can`t get it with this example to place it into the pagination.
<?php
foreach($result as $row) {
echo '
<div class="card"><button1>
'. $row['notice_id'] .'
<div class="time-left">
<div class="dropdown1">
' ;
}
}
else {
echo '';
}
$conn->close();
?>
</div></div>
This is the code from data.php I think I need to place some code into for detection from the ID
<?php
//include configuration file
require 'configuration.php';
$start = 0; $per_page = 1;
$page_counter = 0;
$next = $page_counter + 1;
$previous = $page_counter - 1;
if(isset($_GET['start'])){
$start = $_GET['start'];
$page_counter = $_GET['start'];
$start = $start * $per_page;
$next = $page_counter + 1;
$previous = $page_counter - 1;
}
// query to get messages from messages table
$q = "SELECT * FROM group_notice LIMIT $start, $per_page";
$query = $db->prepare($q);
$query->execute();
if($query->rowCount() > 0){
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
// count total number of rows in students table
$count_query = "SELECT * FROM group_notice";
$query = $db->prepare($count_query);
$query->execute();
$count = $query->rowCount();
// calculate the pagination number by dividing total number of rows with per page.
$paginations = ceil($count / $per_page);
?>
You can use some formulas for calculate limit and offset of results.
For example you have 100 records, and you want to paginate it into 10 records per page, and the formula is like below.
// Get Page from Query String
$page = 1;
if(!empty($_GET["page"])){
$page = $_GET["page"];
}
// Get record count
$count_query = "SELECT * FROM group_notice";
$query = $db->prepare($count_query);
$query->execute();
$count = $query->rowCount();
$per_page = 10; // records per page
$pages = ceil($count/$per_page); // get total page
$start = $page * $per_page - $per_page; // get offset
// Do something with your records
$query = db->prepare("SELECT * FROM group_notice LIMIT ?, ?");
$query->bind_param("ii", $start, $per_page); // you should use bind param if you use prepared statement
$query->execute();
if($query->rowCount() > 0){
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
if($page > 1){
echo 'Prev'; // Print Prev Page
}
for($i = 1; $i <= $pages){
echo ''.$i.''; // Print Page Number
}
if($page < $pages){
echo 'Next'; // Print Next Page
}
Hope it helps.

php postgres SQL pagination

I need a pagination based on php/postgres.
With the code below, I can break de records but only shows the page 1 (link).
Any idea to fix this?
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 5;
$query = pg_query($dbconn,"select * from my table limit 5 offset 0") or die(pg_result_error($dbconn));
$total_query = pg_num_rows($query);
$total_pages = ceil($total_query / 5);
the query result:
while($row = pg_fetch_assoc($query)){
...
}
for the pagination:
for ($i=1; $i<=$total_pages; $i++) {
echo "".$i." ";
}
I don't understand your code very well but the basic logic for a pagination sql query is
Select * from pages limit $page_size offset $page_size*($page_no-1);
I've fix it.
The code:
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$recortds = 10; // change here for records per page
$start_from = ($page-1) * $records;
$qry = pg_query($dbconn,"select count(*) as total from table");
$row_sql = pg_fetch_row($qry);
$total_records = $row_sql[0];
$total_pages = ceil($total_records / $records);
$select = pg_query($dbconn,"select * from table limit $records offset $start_from");
the select result:
while($row = pg_fetch_assoc($select )){
echo $row['col1'].' | '.$row['col2'].' | '.$row['col3'].'<br />';
}
the pagination links:
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='index.php?page=".$i."' class='yourclass'>".$i."</a> ";
}

PHP pagination script not work for search

I used this code in my all pages. Everywhere this code work well. In case of my search page this code count all page by search words but when I click next(2nd or 3rd) page, its cannot display any item. That means sql query for 2nd or 3rd or any others pages not worked. No error also. Pagination page url goes well also.
My Search code:
if(isset($_POST['searchword'])){
$w = mysqli_real_escape_string($dbh, $_POST['searchword']);
$q = strip_tags($w);
$q = trim ($w);
$limit = 12;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $limit;
$sql = "SELECT * FROM search_data WHERE MATCH(detail) AGAINST('+$q*' IN BOOLEAN MODE) ORDER BY id ASC LIMIT $start_from, $limit";
$execute = $dbh->query("$sql");
$rowcount = $execute->num_rows ;
if ($rowcount > 0 ) {
$row = $dbh->query($sql) ;
while ($row = $execute->fetch_assoc()) {
$detail = $row['detail'];
$url = $row['url'];
echo $detail;
}
}
}
//Pagination
$sql = "SELECT COUNT(id) FROM search_data WHERE MATCH(detail) AGAINST('+$q*' IN BOOLEAN MODE)";
$result = mysqli_query($dbh,$sql);
$row = mysqli_fetch_row($result);
$total_records = $row[0];
if($total_records > 0){$total_pages = ceil($total_records / $limit); }
$pagLink = "<ul class='pagination'>";
if(!empty($total_pages)){for ($i=1; $i<=$total_pages; $i++) {
$pagLink .= "<li><a href='".$thispage."?page=".$i."'>".$i."</a> </li>";
};
echo $pagLink . "</ul>";
}

Categories