Using Count giving wrong number of rows - php

Before I was using this code to count rows
echo $db_handle->numRows("SELECT * FROM orders WHERE DATE(reattemptdate) = CURDATE()");
than i found it effects on performance, than i tried to use below code, but it not giving correct number of rows, what wrong i done in below code ?
$sqldelivery = "SELECT COUNT(*) as count FROM orders WHERE DATE(reattemptdate) = CURDATE()";
$resultdeliverys = $db_handle->runSelectQuery($sqldelivery);
$numrowsresultdelivery =count($resultdeliverys);
echo $numrowsresultdelivery;
Database connection code :
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}

In your second code, the query will always return 1 row - a row with the column count being the number of rows, so...
$numrowsresultdelivery =count($resultdeliverys);
Will probably always be 1, you need something like...
$numrowsresultdelivery =$resultdeliverys[0]['count'];
to extract the count field from the first row of the result.
(Note I don't know if this is the right notation, but it's the principle of needing a field from the result rather than the number of results.)

You must already have the count number via $resultdeliverys->count.
$sqldelivery = "SELECT COUNT(*) as count FROM orders WHERE DATE(reattemptdate) = CURDATE()";
$resultdeliverys = $db_handle->runSelectQuery($sqldelivery);
// Try this to know if it's returning array or object
var_dump($resultdeliverys);

Related

How do you do a count query in php with a where clause?

So I have this query like this
$sql2 = "SELECT count(*) FROM comments WHERE YourUsername = '$MyUsername' AND PostId = '$PostId'";
if ($result2=mysqli_query($conn,$sql2))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result2);
echo $rowcount;
}
and I have 2 rows in my database which meet the clause requirements but for some reason it keeps outputting 1 as the result. How do I make it display the actual count and not just 1 when in reality the count is 2 and so on for future rows.
You're SELECTing the count of the rows in your first line, so when the query is run, it's returning the row count into $result2. You don't need to use mysqli_num_rows.
Foul

SQL count all doesn't execute in php

if($sql = $db->query("Count (*) FROM post_items")){
echo mysqli_num_rows($sql);
}
what's wrong with my code? is this the correct way to echo the total of row in a table?
Your query should be
select count(*) FROM post_items
but echoing
mysqli_num_rows($sql);
will always give 1 as the ans, because count function returns only one row.
Rather fetch the details and show the count
$row = $sql->fetch_row();
echo $row[0];
No it is not; you will always get a return value of 1.
Why? Because you are in essence double-counting. The query executes a COUNT aggregate on the table returning a single row with the counted number. mysqli_num_rows is then counting the number of rows in this result set - the single row - and returns 1.
Try, the following line instead, which should fetch the first (only) column returned of the first (only) row in the result set.
echo $sql->fetch_row()[0]
Note you're also missing a SELECT keyword in your SQL statement.
It should be
if($sql = $db->query("select count(*) FROM post_items")){
echo mysqli_num_rows($sql);
}

MySQL COUNT query results in 1 always

I'm wondering why my MySQL COUNT(*) query always results in ->num_rows to be equal 1.
$result = $db->query("SELECT COUNT( * ) FROM u11_users");
print $result->num_rows; // prints 1
Whereas fetching "real data" from the database works fine.
$result = $db->query("SELECT * FROM u11_users");
print $result->num_rows; // prints the correct number of elements in the table
What could be the reason for this?
Because Count(*) returns just one line with the number of rows.
Example:
Using Count(*) the result's something like the following.
array('COUNT(*)' => 20);
echo $result['COUNT(*)']; // 20
Reference
It should return one row*. To get the count you need to:
$result = $db->query("SELECT COUNT(*) AS C FROM u11_users");
$row = $result->fetch_assoc();
print $row["C"];
* since you are using an aggregate function and not using GROUP BY
that's why COUNT exists, it always returns one row with number of selected rows
http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html
Count() is an aggregate function which means it returns just one row that contains the actual answer. You'd see the same type of thing if you used a function like max(id); if the maximum value in a column was 142, then you wouldn't expect to see 142 records but rather a single record with the value 142. Likewise, if the number of rows is 400 and you ask for the count(*), you will not get 400 rows but rather a single row with the answer: 400.
So, to get the count, you'd run your first query, and just access the value in the first (and only) row.
By the way, you should go with this count(*) approach rather than querying for all the data and taking $result->num_rows; because querying for all rows will take far longer since you're pulling back a bunch of data you do not need.

How to do a num_rows() on COUNT query in codeigniter?

This works:
$sql = "SELECT id
FROM `users`
WHERE `account_status` = '" . $i . "'";
$query = $this->db->query($sql);
var_dump($query->num_rows());
But this doesn't:
$sql = "SELECT COUNT(*)
FROM `users`
WHERE `account_status` = '" . $i . "'";
$query = $this->db->query($sql);
var_dump($query->num_rows());
How to do a num_rows on a COUNT(*) query? Also is doing it the 2nd way any better performance wise?
Doing a COUNT(*) will only give you a singular row containing the number of rows and not the results themselves.
To access COUNT(*) you would need to do
$result = $query->row_array();
$count = $result['COUNT(*)'];
The second option performs much better since it does not need to return a dataset to PHP but instead just a count and therefore is much more optimized.
In CI it's really simple actually, all you need is
$this->db->where('account_status', $i);
$num_rows = $this->db->count_all_results('users');
var_dump($num_rows); // prints the number of rows in table users with account status $i
$query->num_rows()
The number of rows returned by the query. Note: In this example, $query is the variable that the query result object is assigned to:
$query = $this->db->query('SELECT * FROM my_table');
echo $query->num_rows();
num_rows on your COUNT() query will literally ALWAYS be 1. It is an aggregate function without a GROUP BY clause, so all rows are grouped together into one. If you want the value of the count, you should give it an identifier SELECT COUNT(*) as myCount ..., then use your normal method of accessing a result (the first, only result) and get it's 'myCount' property.
As per CI Docs we can use the following,
$this->db->where('account_status', $i); // OTHER CONDITIONS IF ANY
$this->db->from('account_status'); //TABLE NAME
echo $this->db->count_all_results();
If we want to get total rows in the table without any condition, simple use
echo $this->db->count_all_results('table_name'); // returns total_rows presented in the table
it's my way of solving the above given question
model
$this->db->select('count(id) as ids');
$this->db->where('id', $id);
$this->db->from('your_table_name');
thanks
This will only return 1 row, because you're just selecting a COUNT(). you will use mysql_num_rows() on the $query in this case.
If you want to get a count of each of the ID's, add GROUP BY id to the end of the string.
Performance-wise, don't ever ever ever use * in your queries. If there is 100 unique fields in a table and you want to get them all, you write out all 100, not *. This is because * has to recalculate how many fields it has to go, every single time it grabs a field, which takes a lot more time to call.
I'd suggest instead of doing another query with the same parameters just immediately running a SELECT FOUND_ROWS()
$list_data = $this->Estimate_items_model->get_details(array("estimate_id" => $id))->result();
$result = array();
$counter = 0;
$templateProcessor->cloneRow('Title', count($list_data));
foreach($list_data as $row) {
$counter++;
$templateProcessor->setValue('Title#'.$counter, $row->title);
$templateProcessor->setValue('Description#'.$counter, $row->description);
$type = $row->unit_type ? $row->unit_type : "";
$templateProcessor->setValue('Quantity#'.$counter, to_decimal_format($row->quantity) . " " . $type);
$templateProcessor->setValue('Rate#'.$counter, to_currency($row->rate, $row->currency_symbol));
$templateProcessor->setValue('Total#'.$counter, to_currency($row->total, $row->currency_symbol));
}

show 2 random rows instead of one

MY SQL QUERY:
$q = mysql_query("SELECT * FROM `ads` WHERE keywords LIKE '%$key%' ORDER BY RAND()");
RESULTS: KEYWORD123
This query searches and results in one random row but i want to show 2 random rows.
How to do that?
any solution?
how??
im grabbing it using this
$row = mysql_fetch_array($q); if ($row
<= 0){ echo 'Not found'; }else{ echo
$row['tab']; }
That query (as-is) will return more than one row (assuming more than one row is LIKE %$key%). If you're only seeing one record, it's possible you're not cycling through the result set, but rather pulling the top response off the stack in your PHP code.
To limit the response to 2 records, you would append LIMIT 2 onto the end of the query. Otherwise, you'll get every row that matches the LIKE operator.
//Build Our Query
$sql = sprintf("SELECT tab
FROM ads
WHERE keyword LIKE '%s'
ORDER BY RAND()
LIMIT 2", ('%'.$key.'%'));
// Load results of query up into a variable
$results = mysql_query($sql);
// Cycle through each returned record
while ( $row = mysql_fetch_array($result) ) {
// do something with $row
echo $row['tab'];
}
The while-loop will run once per returned row. Each time it runs, the $row array inside will represent the current record being accessed. The above example will echo the values stored in your tab field within your db-table.
Remove your order by and add a LIMIT 2
That happens after the execution of the SQL.
Right now you must be doing something like
$res = mysql_query($q);
$r = mysql_fetch_array($res);
echo $r['keywords'];
what you need to do
$q = mysql_query("SELECT * FROM ads WHERE keywords LIKE '%$key%' ORDER BY RAND() LIMIT 2");
$res = mysql_query($q);
while($r = mysql_fetch_array($res)){
echo "<br>" . $r['keywords'];
}
Hope that helps
This query will return all rows containing $key; if it returns only one now this is simply by accident.
You want to add a LIMIT clause to your query, cf http://dev.mysql.com/doc/refman/5.0/en/select.html
Btw both LIKE '%... and ORDER BY RAND() are performance killers

Categories