Get count query results via getSingleScalarResult() and groupBy() - exception - php

I want get results of my query (with limit 10) + count possible results.
I know there is similar questions and answers.
for example here
but if i trying get count possible rows (via getSingleScalarResult()) i will get excepton: The query returned multiple rows. Change the query or use a different result function like getScalarResult().
$query = $repository
->createQueryBuilder('t')
->select('COUNT(t.katId)', 't.hotel', 't.title', 't.desc', 'picture', 'MIN(t.price) AS price');
$query->where('t.visible = (:visible)')->setParameter('visible', 1);
// + some wheres, where in, more than....
$query->groupBy('t.hotel');
$query->setMaxResults(10);
echo $query->getQuery()->getSingleScalarResult();
exit();
I just need one integer whitch represent all results from my query.
How can i get this count number? Ideal in one shot to db.
EDIT:
if i remove $query->groupBy('t.hotel'); and in select keep only ->select('count(t.katId)'); then it work. But i need groupBy because it makes real count of results.
SOLUTION
I divided it on two queries so - to get results i rolled back changes to state before trying any count information, and make clone this query (before set setMaxResults and groupBy), change select (keep all wheres) and get count information.
I will be grateful if someone offers better solution
Get results:
removed COUNT() from select
asking for results changed to 'normal' ->getArrayResults
Get count:
$q = clone $query;
$q->select('count(distinct t.hotel) as count');
$r = $q->getQuery()->getArrayResult();
echo $r[0]['count'];
exit();

If you need keep the groupBy:
$query = $repository->createQueryBuilder('t')
$query->select('COUNT(t.katId)', 't.hotel', 't.title', 't.desc', 'picture', 'MIN(t.price) AS price');
$query->from(ENTITY STRING, 't', 't.hotel'); //here defined your array result key
$query->where('t.visible = (:visible)')->setParameter('visible', 1);
$query->groupBy('t.hotel');
$query->setMaxResults(10);
echo $query->getQuery()->getScalarResult();
exit();
Edit : New edit works ?

You are only interested in COUNT(t.katId), so you should drop other returned fields 't.hotel', 't.title', etc.
The result will then contain a single return value (single scalar result), so $query->setMaxResults(10) is not needed.

Related

how to subtract a specific amount from the COUNT(*) result

I'm new to PHP and i want to know how i can subtract a specific amount from the results from counting the total amount of rows in a table. In this case i'd like to minus the value 3 from whatever the value of the total rows is. But i keep getting an error. Below is my code.
$cartwork = $con->query("SELECT count(*) FROM table");
$vs = '3';
$camount = $cartwork - $vs;
echo "$camount";
When the code runs i get the error "Object of class mysqli_result could not be converted to int" what can i do to fix this and get it to work properly.
The query returns a result set. You need to parse through the result set(s) in order to access the values returned. That's basically what the error states.
Please see here for documentation on the PHP function for fetching rows:
http://php.net/manual/en/function.mysql-fetch-row.php
So basically you would need
$row=$cartwork->mysql_fetch_row();
$cartWork_value = $row[0];
$vs = '3';
$camount = $cartwork_Value - $vs;
echo "$camount";
Note - this assumes that you get back exactly one result row (which should be the case with your query).
You can simply change your query to:
$cartwork = $con->query("SELECT count(*)-3 FROM table");
It doesn't smell particularly good though.

count of subquery in doctrine - querybuilder

I have simple query:
$this->qb->select('l.value')
->addSelect('count(l) AS cnt')
->addSelect('hour(l.time) AS date_hour')
->from(Logs::class, 'l')
->where('l.header = :header')
->groupBy('l.value')
->addGroupBy('date_hour')
->setParameter('header', 'someheader')
This code select 3 columns have one condition and two groupBy.
I want get records count of this query. Of course I dont want to download all records and check size of downloaded data.
Question:
How to rebuild this query and get result from db as singleScalarValue()?
I think you should use (id column for count) here:
->addSelect('count(l) AS cnt')
Something like this, but if you show your Entity i can suggest right solution:
$this->qb->select('l')
->addSelect('count(l.id) AS cnt')
->addSelect('hour(l.time) AS date_hour')
->from(Logs::class, 'l')
->where('l.header = :header')
->groupBy('l.value')
->addGroupBy('date_hour')
->setParameter('header', 'someheader')
$count = $qb->getQuery()->getSingleScalarResult();
Since GROUP BY + COUNT + getSingleScalarResult does not seem to work together in DQL queries, I guess your best option is to count afterwards
$sub
->select('l.id')
->addSelect('l.value as hidden val')
->addSelect('hour(l.time) AS hidden date_hour')
->from(Logs::class, 'l')
->where('l.header = :header')
->groupBy('val')
->addGroupBy('date_hour')
->setParameter('header', 'someheader')
;
$subIds = array_column($sub->getQuery()->getResult(), 'id');
$count = count($subIds);

How to select random rows from a table in MySQL

I am creating a project which involves getting some questions from mysql database. For instance, if I have 200 questions in my database, I want to randomly choose 20 questions in such a way that no one question will be repeated twice. That is, I want to be able to have an array of 20 different questions from the 200 I have every time the user tries to get the list of questions to answer. I will really appreciate your help.
SELECT * FROM questions ORDER BY RAND() LIMIT 20;
PS^ This method not possible for very big tables
Use Google to find a function to create an array with 20 unique numbers, with a minimum and a maximum. Use this array to prepare an SQL query such as:
expression IN (value1, value2, .... value_n);
More on the SQL here.
Possible array filling function here too.
Assuming you have contiguously number questions in your database, you just need a list of 20 random numbers. Also assuming you want the user to be able to take more than one test and get another 20 questions without duplicates then you could start with a randomised array of 200 numbers and select blocks of 20 sequentially from that set i.e.
$startQuestion=1;
$maxQuestion=200;
$numberlist= range(1,$maxQuestion);
shuffle($numberlist);
function getQuestionSet( $noOfQuestions )
{
global $numberlist, $maxQuestion, $startQuestion;
$start= $startQuestion;
if( ($startQuestion+$noOfQuestions) > $maxQuestion)
{
echo "shuffle...\n";
shuffle($numberlist);
$startQuestion=1;
}else
$startQuestion+= $noOfQuestions;
return array_slice($numberlist,$start,$noOfQuestions);
}
// debug...
for($i=0; $i<42; $i++)
{
$questionset= getQuestionSet( 20 );
foreach( $questionset as $num )
echo $num." ";
echo "\n";
}
then use $questionset to retrieve your questions
If you know how many rows there are in the table, you could do use LIMIT to your advantage. With limit you specify a random offset; syntax: LIMIT offset,count. Example:
<?php
$totalRows = 200; // get his value dynamically or whatever...
$limit = 2; // num of rows to select
$rand = mt_rand(0,$totalRows-$limit-1);
$query = 'SELECT * FROM `table` LIMIT '.$rand.','.$limit;
// execute query
?>
This should be safe for big tables, however it will select adjacent rows. You could then mix up the result set via array_rand or shuffle:
<?php
// ... continued
$resultSet = $pdoStm->fetchAll();
$randResultKeys = array_rand($resultSet,$limit); // using array_rand
shuffle($resultSet); // or using shuffle
?>

php +codeigniter sql query

I want to do a query in my model from a table known as jurisdictions. Now I want this query to provide a valid MySQL result resource. I.e I want to pass the result to mysql_fetch_array(). If I pass in $query = $this->db->query(). I get an error saying that the passed in argument is invalid. I was wondering how can I convert $query to a MySQL result recource.
Well, if you want to have a MySQL resource, you should be using mysql_query.
Codeigniter already has a method which will give you one row at a time: row_array (actually, it has two, the other is just row, but that returns an object, not an array). If you want to get numeric indexes on the result of result_array, use array_values:
$result = $this->db->query( "SELECT 'foo' as foo_rules FROM DUAL" );
$aso_arr = $result->row_array(); // assoc. array w/o numeric indexes
echo $aso_arr[ 'foo_rules' ];
$num_arr = array_values( $aso_arr );
echo $num_arr[ 0 ];
If you would like the entire result of the selection, then use result and result_array (they have behavior similar to row and row_array, only they return the whole result set in an array)
EDIT
I repeat my first sentence, but you can get the MySQL resource this way:
$result = $this->db->query( "SELECT 'foo' as foo_rules FROM DUAL" );
$resource = $result->result_id;
But, since this is not documented, it should not be considered supported or even expected behavior. Be forewarned.
If I'm understanding you correctly then why not just use the available methods of:
$query->result();
or
$query->result_array();
Choose whichever to suit your needs.

Whats the best way to retrieve information from Sphinx (in PHP)?

I'm new to sphinx, and I'm seting it up on a new website.
It's working fine, and when i search with the search in the console, everything work.
Using the PHP api and the searched, gives me the same results as well. But it gives me only ids and weights for the rows found. Is there some way to bring some text fields togheter with the 'matches' hash, for example?
If there is no way to do this, does anyone have a good idea about how to retrieve the records from the database (sql) in the sphinx weight sort order (searching all them at the same time)?
Yeah, sphinx doesn't bring the results.
But I found out a simple way to reorder the query using the IN() clause, to bring all together.
Quering something
SELECT * FROM table WHERE id IN(id_list... )
just indexing the result, with their id in the table:
while ($row = mysql_fetch_objects)
$result[$row->id] = $row;
and having the matching results from sphinx, its very easy to reorder:
$ordered_result = array();
foreach ($sphinxs_results['matches'] as $id => $content)
$ordered_result[] = $result1[$id];
this shall work, if your $sphinxs_results are in the correct order.
its almost pat's answer, but with less one loop. Can make some diference in big results, I guess.
You can use a mysql FIELD() function call in your ORDER BY to ensure everything is in the order sphinx specified.
$idlist = array();
foreach ( $sphinx_result["matches"] as $id => $idinfo ) {
$idlist[] = "$id";
}
$ids = implode(", ", $idlist);
SELECT * FROM table WHERE id IN ($ids) ORDER BY FIELD(id, $ids)
unfortually sphinx didn't returns matched fields, only its ids (sphinx index didn't contains data - only hash from data).
Post about this issue you can find on the sphinxsearch.com forum.
As Alex says, Sphinx doesn't return that information. You will have to use the IDs to query the database yourself - just loop through each ID, get your relevant data out, keeping the results in weighting order. To do it all in one query, you could try something like the following (psuedo-code - PHP ain't my language of choice):
results = db.query("SELECT * FROM table WHERE id IN (%s)", matches.join(", "));
ordered_results = [];
for (match in matches) {
for (result in results) {
if (result["id"] == match) {
ordered_results << result;
}
}
}
return ordered_results;

Categories