Here is my code:
$query = "SELECT SQL_CALC_FOUND_ROWS 1, id, name
FROM users where id > ?";
$sth = $this->dbh->prepare($query);
$sth->execute([4]);
echo $total_num = $this->dbh->query('SELECT FOUND_ROWS()')->fetchColumn();
//=> 43
My code works as well and prints 43.
My question is, why my code still works when I remove SQL_CALC_FOUND_ROWS 1 from SELECT statement?
$query = "SELECT id, name
FROM users where id > ?";
$sth = $this->dbh->prepare($query);
$sth->execute([4]);
echo $total_num = $this->dbh->query('SELECT FOUND_ROWS()')->fetchColumn();
//=> 43
See? It still prints 43. So is putting SQL_CALC_FOUND_ROWS 1 in the SELECT statement mandatory? Why should we put it there anyway?
Related
Pagination works fine when I don't use the WHERE statement in my SELECT statement. For some reason as soon as I add additional requests in the SELECT statement, only the 1st pagination page works. So it seems like the variable data is lost after the first page is displayed. Below is some of the code:-
<?php
include 'database.php';
include 'paginator.php';
$pdo = Database::connect();
$paginator = new Paginator();
$sql = "SELECT count(*) FROM customer_crm ";
$paginator->paginate($pdo->query($sql)->fetchColumn());
$query = $_GET["query"];
if (isset($query)) {
($_GET['query'])?('%'.$_GET['query'].'%'):'%';
$sql = "SELECT * FROM customer_crm WHERE firstname LIKE :query OR email LIKE :query OR telephone LIKE :query ";
}
else {
$start = (($paginator->getCurrentPage()-1)*$paginator->itemsPerPage);
$length = ($paginator->itemsPerPage);
//$sql = "SELECT * FROM customer_crm WHERE customer_group_id = $input OR date_followup= CURDATE() ORDER BY customer_group_id DESC limit $start, $length ";
$sql = "SELECT * FROM customer_crm ORDER BY date_followup DESC limit $start, $length ";
//$sql = "SELECT * FROM customer_crm WHERE customer_group_id = $input ORDER BY date_followup DESC limit $start, $length ";
}
$sth = $pdo->prepare($sql);
$sth->bindParam(':start',$start,PDO::PARAM_INT);
$sth->bindParam(':length',$length,PDO::PARAM_INT);
$sth->bindParam(':query',$query,PDO::PARAM_STR);
$sth->execute();
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
Without knowing which Paginator are we talking about, I could only advise you to do something like
include 'database.php';
include 'paginator.php';
$pdo = Database::connect();
$paginator = new Paginator();
$query = (isset($_GET["query"]) && strlen($_GET["query"])>1)? '%'.$_GET["query"].'%':'%';
$countsql = "SELECT * FROM customer_crm WHERE firstname LIKE :query OR email LIKE :query OR telephone LIKE :query ";
$sthcount = $pdo->prepare($countsql);
$sthcount->bindParam(':query',$query,PDO::PARAM_STR);
$sthcount->execute();
$count=$sthcount->fetchColumn();
$paginator->paginate($count);
$start = (($paginator->getCurrentPage()-1)*$paginator->itemsPerPage);
$length = ($paginator->itemsPerPage);
$sql = $countsql . ' ORDER BY date_followup DESC limit :start, :length ';
$sth = $pdo->prepare($sql);
$sth->bindParam(':start',$start,PDO::PARAM_INT);
$sth->bindParam(':length',$length,PDO::PARAM_INT);
$sth->bindParam(':query',$query,PDO::PARAM_STR);
$sth->execute();
See, you where making two mistakes here:
getting your count value without considering the query. You should set the value of $query regardless of the existance of $_GET['query'], and use it in your count query as well as your results query.
binding parameters whose placeholders and values do not exist in the query you're executing. Make sure your results query contains :query, :start and :length or you will be binding more parameters than the query has.
You should also have wrapped your statements in try/catch blocks so you could debug what was happening.
try {
$sth = $pdo->prepare($sql);
$sth->bindParam(':start',$start,PDO::PARAM_INT);
$sth->bindParam(':length',$length,PDO::PARAM_INT);
$sth->bindParam(':query',$query,PDO::PARAM_STR);
$sth->execute();
} catch(\PDOException $e) {
die('Error in query: '. $e->getMessage());
}
That way you would have known that the query was failing because of
Invalid parameter number: parameter was not defined
NOTE I have no clue about how your paginator will know about the current page, nor can I see where are you setting the itemsPerPage value.
In my PHP code I run the following statement:
$stmt = $pdo->prepare("SELECT * FROM `tb_services` WHERE tb_services.user_id = :var1 AND
(tb_services.user_id = :var1 OR tb_services.user_id = (SELECT subuser_owner_id FROM tb_users WHERE user_id = :var1))
AND tc_services.sub_id = :var2");
$stmt->bindParam(":var1", $_GET['var1']);
$stmt->bindParam(":var2", $_GET['var2']);
However doing $stmt->rowCount() returns 0, but when I run this exact statement(filled with the same values that I'm inputting instead of the :var1, :var2) it finds the row perfectly.
while($info = $stmt->fetch(PDO::FETCH_ASSOC)) {
The above is the code that is not running. As the return of the rowCount() is 0 and the while loop is not running, that just shows to me that it is for some reason not finding the row. If I input static values into the SQL statement, it works perfectly.
I have found the error. I was overlooking my code and saw the stupid mistake I made. For anyone out there that might experience a similar problem, the following MySQL statement:
$stmt = $pdo->prepare("SELECT * FROM `tb_services` WHERE tb_services.user_id = :var1 AND
(tb_services.user_id = :var1 OR tb_services.user_id = (SELECT subuser_owner_id FROM tb_users WHERE user_id = :var1))
AND tc_services.sub_id = :var2");
should be
$stmt = $pdo->prepare("SELECT * FROM `tb_services` WHERE(tb_services.user_id = :var1 OR tb_services.user_id = (SELECT subuser_owner_id FROM tb_users WHERE user_id = :var1))
AND tc_services.sub_id = :var2");
Removing the first tb_services.user_id = :var1 as that caused the error.
I am trying to run this Query:
$stmt = $conn->prepare("SELECT COUNT(*) as a from session ");
$stmt->execute(array());
$records = $stmt->fetch();
echo '- '.$result["a"];
but its just displaying:
-
on its own, with no number of records, i know there is rows because when i run
SELECT COUNT(*) from `session` as a
in PHPMyAdmin it shows all the rows there in the column a
why would this query not work?
Here you go for a single column result you can use fetchColumn() and also you have aliased the table name not the column name
$stmt = $conn->prepare("SELECT COUNT(*) as a from `session`");
$stmt->execute(array());
echo $stmt->fetchColumn();
PDOStatement::fetchColumn
try this
$stmt = $conn->prepare("SELECT COUNT(*) as cnt from `session` ");
$stmt->execute(array());
$records = $stmt->fetch();
echo '- '.$records["cnt"];
why you are echoing $result.. you havent declared it..
use $records
echo '- '.$records["a"];
Try like this
$stmt = $conn->prepare("SELECT COUNT(*) as a from `session` ");
$stmt->execute(array());
$records = $stmt->fetch();
echo '- '.$records["a"];
hello can i merge those 2 queries in one query my first query get the number of articles in database and second query get the sum of all visits of all article whats the best method to make it one query
$stmt = $db->query('SELECT * FROM stories');
$story_count = $stmt->rowCount();
$stmt = $db->query("SELECT sum(visits) FROM stories");
$total_visits = $stmt->fetchColumn();
Try like
$stmt = $db->query('SELECT COUNT(*) as total_cnt,
SUM(visits) as total_visits FROM stories');
then excute your query,you will get result from "total_cnt" and "total_visits"
SELECT COUNT(*) as total, SUM(visits) as total_visits FROM stories;
SELECT Story.*, COUNT(*) as total, SUM(Story.visits) as total_visits FROM stories AS Story;
If you want to get other fields along with SUM and COUNT use .*.
Yes try this:
$stmt = $db->query('SELECT count(*),sum(visits) FROM stories');
$result = $stmt->fetch_array(MYSQLI_NUM);
$story_count = $result[0];
$total_visits = $result[1];
I've a PHP application that works with MySQL through PDO. I have a table with different records and I have to prevenet inserting a duplicate one. But when I want to check existing items, select statement does not return a true value. This is my code:
$sql = "SELECT COUNT(id) FROM tbl_product_category1 WHERE title = '?'";
$q = $db->prepare($sql);
$q->execute(array($title));
if ($q->fetchColumn() == 0)
{
...
I also tested this one:
$sql = "SELECT id FROM tbl_product_category1 WHERE title = '?'";
$q = $db->prepare($sql);
$q->execute(array($title));
$rows = $q->rowCount();
if ($rows == 0)
{
...
Imagine $title=1. I have 4 records with this value. But I can not see anything in SELECT statement. What is wrong here ?
try this: (don't wrap the value of the title with single quotes)
$sql = "SELECT COUNT(id) FROM tbl_product_category1 WHERE title = ? ";