make this code PDO friendly - php

I've just started using PDO instead of the mysql functions. But now I'm stuck on a part of my php blog.
How would I make this code a little more PDO friendly:
$total_results = mysql_fetch_array(mysql_query("SELECT COUNT(*) as num
FROM php_blog"));
$total_pages = ceil($total_results['num'] / $blog_postnumber);
for($i = 1; $i <= $total_pages; $i++) {
if ($page == $i) {
echo "<span class='current'>$i</span>";
}
else {
echo "$i";
}
}
I tried with PDO rowCount(), but it doesn't seem to work...
Sorry for my poor english, I'm from Sweden!

rowCount doesn't work with mySQL in PDO. Instead, you just run the count(*) query.
<?php
$sql = "SELECT count(*) FROM `table` WHERE foo = bar";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
Source: Row count with PDO

$stmt = $db->exec( "select count(*) as num from php_blog" );
$results = $stmt->fetch();
$total_results = $results[ 'num' ];
$total_pages = ceil( $total_results / $blog_postnumber );
for($i = 1; $i <= $total_pages; $i++) {
if ($page == $i) {
echo "<span class='current'>$i</span>";
}
else {
echo "$i";
}
}

Related

How do I display content with PDO based on num_rows?

Apparently, the num_rows property does not work in PDO as it would with mysqli.
Normally, with mysqli, my code would look like this:
<?php
$conn = new mysqli('127.0.0.1','root','mypassword','mydbname');
if($conn->connect_errno){
die("Sorry, could not connect.");
}
$id = 1;
$qry = "SELECT * FROM customers WHERE id = ?";
$getCustomers = $conn->prepare($qry);
$getCustomers->bind_param("i",$id);
$getCustomers->execute();
$result = $getCustomers->get_result();
$count = $result->num_rows;
if($count == 0){
echo "Sorry, there are no results";
}else{
while($row = $result->fetch_object()){
echo $row->id;
echo $row->fname;
echo $row->lname;
echo $row->entry_date;
}
}
?>
How do I create the equivalent with PDO? Here is what I have tried so far:
<?php
try{
$conn = new PDO('mysql:host=127.0.0.1;dbname=mydbname','root','mypassword');
}catch(PDOException $e){
echo $e;
}
$id = 1;
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$rows = $qry->fetchAll(PDO::FETCH_OBJ);
$count = count($rows);
if($count == 0){
echo "Sorry, there are no results for your criteria";
}else{
for($i = 0; $i < $count; $i++){
echo $rows->fname;
}
}
?>
Yeah isn't PDO great ;p no need to count rows when you have already got them.
To loop over your result as you have an array.
Change:
for ($i = 0; $i < $count; $i++){
echo $rows->fname;
}
To:
for ($i = 0; $i < $count; $i++){
echo $rows[$i]->fname;
}
Or better just use a foreach.
foreach ($rows as $row) {
echo $row->fname;
}
The statement
fetchAll(PDO::FETCH_OBJ) returns an array containing all of the result set rows as described here. To get the size of the array use sizeof($count). That should give you the size of the array.
To answer your question specifically. You can use rowCount() to retrieve the number of rows in a result:
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$count = $qry->rowCount();
$rows = $qry->fetchAll(PDO::FETCH_ASSOC); //my personal preference
for($i=0; $i < $count; $i++) {
echo $rows[$i]['fname'];
}
To more closely replicate your mysqli code:
while($row = $qry->fetch(PDO::FETCH_OBJ) {
echo $row->fname;
}
Of course, you should always check $conn->errorCode() after each database execution to ensure something go sideways on you.
UPDATE:
As Lawrence points out, rowCount() does not work with MS SQL Server. An alternative in that case is to use fetchAll() and count().

PHP Pagination with SQL_CALC_FOUND_ROWS and LIMIT

Hello my dear friends,
My goal is to paginate through my database entries, while using SQL_CALC_FOUND_ROWS and FOUND_ROWS, because I also have a search function
The search results are there, I just cannot paginate through them.
Probably my code is a total mess for the PHP Pros here, please don’t worry about commenting on that. Any help is greatly appreciated. I am just starting out on PHP and I am highly motivated to become a Pro one day as well.
What is it that I have to do in order to make the pagination work, so that I can paginate while having a search function on the page?
DETAILS:
check for the page
get the search
SEARCH FORM submit to same page
pagination and search are meant to work in unity
LIMIT in conjunction with SQL_CALC_FOUND_ROWS
LIKE to filter search results
prepared statements
while loop displays results with PDO fetch
FOUND_ROWS to get result of first query
--> that result is an Integer
last page is calculated by dividing
that Integer through the limit
pagination is done inside for loop with if statements
connect
try {
$conn = new PDO($server, $user, $pass);
$conn -> setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "success";
} catch (PDOException $e) {
echo "ERROR: " . $e -> getMessage();
}
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);
index
if (!isset($_GET['page'])) { $page = 1;
} else { $page = $_GET['page']; }
if ($page < 1) { $page = 1;
} elseif ($page > $last_page) {
$page = $last_page; }
$search = $_GET['search'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="GET">
<input type="text" name="search" value="<?php $search ?>">
<input type="submit" value="search">
</form</body>
</html>
<?php
$start = 0;
$limit = 3;
$query = "
SELECT SQL_CALC_FOUND_ROWS * FROM tbl_articles
WHERE
(art_headline LIKE '%{$search}%')
OR
(art_content LIKE '%{$search}%')
LIMIT $start, $limit
";
$stmt = $conn -> prepare($query);
$stmt -> execute();
while ($res = $stmt -> fetch(PDO::FETCH_ASSOC)) {
echo '<h1>'.$res['art_headline'].'</h1>'."\n";
echo '<p>'.$res['art_content'].'</p>';
echo '<b>'.$res['art_author'].'</b>'."\n";
echo '<span>'.date("d.m.Y", strtotime($res['art_datetime'])).'</span>'."\n\n";
echo '<b>'.$res['art_id'].'</b>'."\n";
}
$query = "
SELECT FOUND_ROWS() AS num FROM tbl_articles
";
$stmt = $conn -> prepare($query);
$stmt -> execute();
$max = $stmt -> fetch(PDO::FETCH_ASSOC);
var_dump($max[num]);
$total_pages = $max[num];
// $stmt = $conn -> query($query) -> fetchColumn();
$last_page = ceil($total_pages / $limit);
// loop through pages
echo "<div><nav>";
for ($i = 1; $i <= $last_page; $i++) {
if (
($i == 1)
||
($i == $last_page)
||
(
($i >= ($page - 2))
&&
($i <= ($page + 2))
)
) {
if ($last_i != ($i - 1)) {
$out .= " ... ";
}
if ($page == $i) { $out .= "["; }
$out .= "$i";
if ($page == $i) { $out .= "] "; }
$out .= " ";
$last_i = $i;
$prev = $page - 1;
$prev_link = "back\n";
$next = $page + 1;
$next_link = "next\n";
}
}
echo $prev_link;
echo $out;
echo $next_link;
echo "</nav></div>";
?>
Any help is greatly appreciated, from a PHP beginner.
ok guys, my PHP Pro Mentor helped me solve it.
Here we go:
to fix the search results display I had to insert
if ($_GET['page'] > 1) {
$start = ($_GET['page'] - 1) * $limit;
}
between the $start and $limit variables and the first $query
to fix the pagination I just had to insert:
$page = $_GET['page'];
on top of the script.

i wrote some code for fetch data from database ,in mysql code is working and in pdo it is not working

This is mysql connection coding, it is working fine
the same code i wrote with pdo connection,it is not working i'm new to php please help me to get out of this problem.
thanks in advance
<?php
error_reporting(0);
ini_set('max_execution_time', 600);
require_once 'config.php';
if(isset($_GET["nm_mask"]))
$nm_mask = $_GET['nm_mask'];
else
$nm_mask = "";
if(isset($_GET["cd_mask"]))
$cd_mask = $_GET['cd_mask'];
else
$cd_mask = "";
if(isset($_GET["func"]))
$func = $_GET['func'];
else
$func = "";
$where = "WHERE 1=1";
if($nm_mask!='')
$where.= " AND Login LIKE '$nm_mask%'";
if($cd_mask!='')
$where.= " AND Manager_Login LIKE '$cd_mask%'";
if($func!='')
$where.= " AND Function LIKE '$func%'";
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1; // connect to the database
$result = mysqli_query("SELECT COUNT(*) AS count FROM EmpMasterTB ".$where);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
if ($limit<0) $limit = 0;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT * from EmpMasterTB ". $where ." ORDER BY $sidx $sord LIMIT $start , $limit";
$result = mysqli_query( $SQL ) or die("Couldn?t execute query.".mysqli_error());
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$responce->rows[$i]['id']=$row[WeekNo].$row[Login];
$responce->rows[$i]['cell']=array($row['WeekNo'],$row['WeekBeginning'],$row['SITE'],$row['Name'],$row['WFH'],$row['Login'],$row['Manager_Login'],$row['Lead'],$row['Cost_center'],$row['Business_Title'],$row['Function'],$row['Workgroup'],$row['Login_time'],$row['ROLE'],$row['Secondary_Skill'],$row['Weekoff'],""); $i++;
}
echo json_encode($responce);
?>
PDO connection code
<?php
error_reporting(0);
ini_set('max_execution_time', 600);
require_once 'config.php';
if(isset($_GET["nm_mask"]))
$nm_mask = $_GET['nm_mask'];
else
$nm_mask = "";
if(isset($_GET["cd_mask"]))
$cd_mask = $_GET['cd_mask'];
else
$cd_mask = "";
if(isset($_GET["func"]))
$func = $_GET['func'];
else
$func = "";
$where = "WHERE 1=1";
if($nm_mask!='')
$where.= " AND Login LIKE '$nm_mask%'";
if($cd_mask!='')
$where.= " AND Manager_Login LIKE '$cd_mask%'";
if($func!='')
$where.= " AND Function LIKE '$func%'";
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1; // connect to the database
$count = $dbh->exec("SELECT COUNT(*) AS count FROM EmpMasterTB ".$where);
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
if ($limit<0) $limit = 0;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT * from EmpMasterTB ". $where ." ORDER BY $sidx $sord LIMIT $start , $limit"; /*** The SQL SELECT statement ***/
$stmt = $dbh->query($SQL); /*** fetch into an PDOStatement object ***/
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
/*** echo number of columns ***/
$obj = $stmt->fetch(PDO::FETCH_OBJ);
/*** loop over the object directly ***/
{
$responce->rows[$i]['id']=$obj->WeekNo.$obj->Login;
$responce->rows[$i]['cell']=array($obj->WeekNo ,$obj->WeekBeginning ,$obj->SITE ,$obj->Name ,$obj->WFH ,$obj->Login ,$obj->Manager_Login ,$obj->Lead ,$obj->Cost_center ,$obj->Business_Title ,$obj->Function ,$obj->Workgroup ,$obj->Login_time ,$obj->ROLE ,$obj->Secondary_Skill ,$obj->Weekoff ); $i++;
}
echo json_encode($ );
?>
You have missed for loop and you didn't pass response in json_encode().
Please check my below code:
/*** echo number of columns ***/
$objs = $stmt->fetch(PDO::FETCH_OBJ);
/*** loop over the object directly ***/
foreach($objs as $obj)
{
$responce->rows[$i]['id']=$obj->WeekNo.$obj->Login;
$responce->rows[$i]['cell']=array($obj->WeekNo ,$obj->WeekBeginning ,$obj->SITE ,$obj->Name ,$obj->WFH ,$obj->Login ,$obj->Manager_Login ,$obj->Lead ,$obj->Cost_center ,$obj->Business_Title ,$obj->Function ,$obj->Workgroup ,$obj->Login_time ,$obj->ROLE ,$obj->Secondary_Skill ,$obj->Weekoff ); $i++;
}
echo json_encode($responce );

Mysql_result() error

I'm trying to get pagination to work on my page, but running into a error:
mysql_result() expects parameter 1 to be resource, object given in
I think I need to use a mysqli command but can't seem to figure it out. Here is my code
$connect = mysqli_connect('localhost', 'root', 'password', 'vdb');
$per_page = 6;
$pages_query = mysqli_query($connect, "SELECT COUNT(id) FROM customers");
$pages = ceil(mysql_result($pages_query, 0) / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$query = mysqli_query($connect, "SELECT cid, fname, lname,address, score FROM customers");
while ($query_row = mysqli_fetch_assoc($query)) {
$array[] = $query_row['fname'] . '<br />';
}
if($pages >= 1)
{
for($x=1; $x <= $pages; $x++)
{
echo '' .$x.'';
}
}
Thanks in Advance!
You are jumbling between mysql and mysqli
$pages_query = mysqli_query($connect, "SELECT COUNT(id) FROM customers"); // MySQLi
$pages = ceil(mysql_result($pages_query, 0) / $per_page); // MySQL
There should be mysqli_result instead of mysql_result. Never mix them up and use just mysqli_* functions.
// line 3 of code above
$pages = ceil(mysqli_result($pages_query, 0) / $per_page);
^^

MySQLi not returning rows in order

This is probably not a very difficult question to answer. I'm having trouble with this PHP function I wrote... it returns the rows line by line, but it's returning them incremented by 4 each time. So the the 1st row will output, then the 5th, then the 9th...
function showDatabases() {
# $_GET variables from the URL.
$database = mysql_real_escape_string($_GET['database']);
$table = mysql_real_escape_string($_GET['table']);
$mysqli = new mysqli('127.0.0.1', 'root', '', $database);
$query_one = $mysqli->query("SELECT * from $table");
$num_rows = mysqli_num_rows($query_one);
$num_fields = mysqli_num_fields($query_one);
for ($x = 0; $x < $num_rows; $x++) {
for ($c = 0; $c < $num_fields; $c++) {
$row = mysqli_fetch_row($query_one);
echo($row[$c]." ");
}
echo("<br/>");
}
}
Thanks!
mysqli_fetch_row fetched an entire row and moves the pointer to the following row. You should call it only once per each row; now you are calling it once per column.
That is,
for ($x = 0; $x < $num_rows; $x++) {
$row = mysqli_fetch_row($query_one);
for ($c = 0; $c < $num_fields; $c++) {
echo($row[$c]." ");
}
echo("<br/>");
}
you are complicating things
you can do it with just one loop
$query = "SELECT * from $table";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row['fieldname']." ";
}
}
I advice you to add order by some time the default order is not the id order.

Categories