can i merge those 2 queries in one query - php

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];

Related

get results from table which other table does not have

I'm trying to compare two arrays:
First array
$query = $db->prepare("SELECT vraagnummer FROM insertquestion");
$query->execute();
$fetch_query = $query->fetchAll(PDO::FETCH_ASSOC);
Second array
$query = $db->prepare("SELECT vraagnummer FROM vraag");
$query->execute();
$fetch_query_exists = $query->fetchAll(PDO::FETCH_ASSOC);
I want to receive all the results of $fetch_query exept for the ones that are in fetch_query_exists
I tried using:
$result=array_diff($fetch_query ,$fetch_query_exists );
But no results are displayed, just an empty array.
So how do I fetch the results of fetch_query excluding the ones that exist in fetch_query_exists ?
You can do it in single query using NOT IN
SELECT vraagnummer FROM insertquestion
WHERE vraagnummer NOT IN(SELECT vraagnummer FROM vraag)
In addition to #Saty's answer I believe the following would also do the trick without the subselect.
SELECT i.vraagnummber
FROM insertquestion i
LEFT JOIN vraag v
ON v.vraagnummer = i.vraagnummer
WHERE v.vraagnummer IS NULL;
Maybe that, but not sure:
$query = $db->prepare("SELECT vraagnummer FROM insertquestion RIGHT JOIN vraag ON insertquestion.vraagnummer = vraag.vraagnummer");
$query->execute();
$fetch_query = $query->fetchAll(PDO::FETCH_ASSOC);
If you don't want to use a single query then use this:
$result = array_diff_assoc($fetch_query , $fetch_query_exists );

How can I add other data after the resulting query

I have this query.
$stmt = $this->getconnection()->prepare("SELECT * FROM detailuser where id = ?");
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
and I want to add amount in the result after the dateadded, but I am confuse how to add the amount. the amount is in another table and I have no reference on the first table (detailuser)
$amount = 100;
$rec = array(
'data'=>$result,
);
echo json_encode($rec);
{"data":[{"firstname":"Alex","friendname":"Alice","amount_due":"600.00","dateadded"
:"2015-09-14 13:30"},{"firstname":"Annie","friendname":"Karren","amount_due":"600
.00","dateadded":"2015-09-14 13:30"},{"firstname":"Helen","friendname":"Alice","amount_due":"600.00","dateadded":"2015-09-14 13:30"}]}
Thank you in advance
You can prepare a SELECT statement to fetch all rows and in that statement, you can add your dummy column.
SELECT *, 100 AS 'amount' FROM table_name
Instead of abusing your SELECT statement you can also loop over your result set.
foreach ( $result as $row ){
$row['amount'] = 100;
}
//encode and output
Use PDO prepare and then fetchAll() results!
$stmt= $dbh->prepare("SELECT firstname, friendname, amount_due, dateadded, "100" AS amount FROM yourTable");
$stmt->execute();
$result = $stmt->fetchAll();

PHP FOUND_ROWS and COUNT in same SELECT

I have this code:
$sql = "SELECT FOUND_ROWS() AS totalRows, COUNT(*) AS totalRefunds FROM table WHERE result = 'refunded'";
$totalRows = $conn->query( $sql )->fetch();
$totalRefunds = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0], "totalRefunds" => $totalRefunds[0] ) );
I want totalRows = 7 and totalRefunds = 1 but the above returns 0 for both. If I remove either the FOUND_ROWS() or COUNT(*) statements then the other one works. I'm guessing there's something wrong in SELECT but not sure what it is. Or maybe something else is wrong???
Thanks in advance.
To obtain this row count, include a SQL_CALC_FOUND_ROWS option in the SELECT statement, and then invoke FOUND_ROWS() afterward
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM table WHERE result = 'refunded'";
and then SELECT FOUND_ROWS()
Try this way. Assuming you run the query with SQL_CALC_FOUND_ROWS prior to run this
SELECT (#variable := FOUND_ROWS()) AS totalRows, COUNT(*) AS totalRefunds
FROM table WHERE result = 'refunded'
FOUND_ROWS() is used for counting rows as if LIMIT was ignored. It will not append total rows to other query result (unless you select them all, but there's no point if you only need count). Do it simple if you want this information only:
$sql = "SELECT COUNT(*) as totalRows FROM table";
$totalRows = $conn->query( $sql )->fetch();
$sql = "SELECT COUNT(*) as totalRefunds FROM table WHERE result = 'refunded'";
$totalRefunds = $conn->query( $sql )->fetch();
Other way (but different context) is to split counts into all 'result' column types (refunded/not refunded/other..) using GROUP BY so the the total rows can be obtained as sum of single counts returned.

php/mysql not counting rows in table

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

How do I SELECT and COUNT rows in SQL?

How do I get the results and count the results in one query? (Im using PDO statements)
SELECT * FROM table; // gets results
SELECT COUNT(*) FROM table; // counts results
$result = mysql_query( "SELECT * FROM table");
$count = mysql_num_rows( $result);
Using PDO:
$statement = $dbh->prepare('SELECT * FROM table');
$statement->execute();
$count = $statement->rowCount();
This will put the record count at the end of each row.
SELECT *
, COUNT(1) OVER () AS RecordCount
FROM table;
SELECT *, (select count(*) FROM table) ct FROM table
you should execute only one query...
$sql = SELECT * FROM table;
$res = mysql_query($sql);
you can have total count by mysql_num_rows(); function.. like this ..
$count = mysql_num_rows($res);

Categories