I am trying to get some results for a query and count all the data results using PHP.
Actually I'm doing something like this:
$MQ=$cnx->query("SELECT COUNT(id) FROM table WHERE field=1;");
$MFA=$cnx->fetch_row();
$count=$MFA[0];
echo "Showing $count results";
$MQ=$cnx->query("SELECT id,name FROM table WHERE field=1;");
while($MFA=$MQ->fetch_assoc()){
// show something with $MFA[id] and $MFA[name]
}
I want to avoid using 2 queries, Is there any way to get the rows count and then get all the results without using an array?
You can use the num_rows property to get the number of rows in a result set.
$MQ=$cnx->query("SELECT id,name FROM table WHERE field=1;");
$count=$MQ->num_rows;
echo "Showing $count results";
while($MFA=$MQ->fetch_assoc()){
// show something with $MFA[id] and $MFA[name]
}
Is there any way to get the rows count and then get all the results without using an array?
There is, but you don't need it.
In fact, you should use an array, to separate your business logic from presentation logic.
And as long as you have an array, you can always count it's members.
You definitely should quit the practice of showing the query results right during the query execution. Instead, learn logic separation and use of templates.
Related
I do two queries, one to get the count of all results and one to get the actual results 9 by 9.
my problem is when i try to get the count of the results the second query get all the rows.
$courses = $this->load->model("course")->where("deleted",0);
$courses->where("country",strtolower($country));
$courses->count(); // OK
$courses->offset(($per_page)*9)->limit(9);
$courses->get(); // returns 9 rows from all database (like select * from courses limit 9) without where country=france
my problem is I want to count all the results but I want to get just 9 results for pagination purposes
Need detail of your problem you can check the last executed query by running
echo $this->db->last_query();
And then you will be able to trace it.
Assuming that:
$courses = $this->db;
$course->get() will give you full record. If you want count do this:
$query = $course->get();
echo $query->num_rows();//will give you row count
Note: If you want to get all records also you have you use two
separate query for fetching records and getting query.
I would suggest you to use Codeigniter Pagination Class
I'm trying to count the number of rows that are returned to $data in a wordpress database query that I'm making. See below
$data = $wpdb->get_results($wpdb->prepare("SELECT * FROM table WHERE wordpress_id=%d",get_current_user_id()),ARRAY_A);
The issue that I seem to be running into is the use of a prepared statement. I figure I could just write a loop to go through the array and tally them up but is there a more elegant way of doing this?
Many thanks in advance.
If you only need the count, change your SQL query to SELECT COUNT(*) as count .... This is efficient since the counting will be done on the database itself, and you won't be fetching all the data through the network.
If, however, you need both the data and the count, fetch the data as you are, and get the count by doing count($data).
Reference: count()
In my program I launch an SQL query and get back a result resource. I then iterate through the rows of this result resource using the mysql_fetch_array() function and use the contents of the fields of each row to construct a further SQL query.
The result of launching this second query is the first set of results that I want. However, because the number of results produced by doing this is not many I want to make the search less specific by dropping the last record used to make the query.
e.g. the query which produces the first set of results I want could be:
SELECT uid FROM users WHERE (gender=male AND relationship_status=single
AND shoe_size=10)
I would then want to drop the last record so that my query became:
SELECT uid FROM users WHERE (gender=male AND relationship_status=single)
I have already written code to produce the first query but as I mentioned above I use the mysql_fetch_array function to iterate through ALL of the records. In subsequent "rounds" I only want to iterate through successively less records so that my query is less specific. How can I do this?
This seems like an very inefficient method too - so I'm welcome to any simple ideas which might make it more efficient.
EDIT: Thanks for the reply - Yeah I am actually doing this in my program. I am basically trying to implement a basic search algorithm by taking all the preferences a user has specified in the DB and using it to form a query to look for people with those preferences. So the first time search using all the criteria, then on successive attempts search using one less criteria and negate the user ids which were previously returned. At the moment I am constructing the query from scratch for each "round", but I want to find a way I can do this using the last query
Using the queries above, you could do:
SELECT uid
FROM users
WHERE uid NOT IN (
SELECT uid
FROM users
WHERE
(gender=male
AND relationship_status=single
AND shoe_size=10)
)
This will essentially turn your first query into a sub-query, and use that to negate the results returned. Ie, it will return all the rows, NOT IN the first query.
I run a query and get a result set. I need to get the nth record from this result set. Any ideas how I can do this?
I cannot select the nth record from the database directly coz I need to filter it and don't know how many records there are in the result set. So I cannot be certain which number to pass to the mysql_result method i.e.
Based on certain conditions, get a few rows from a table
From these rows, select the nth row (the number n is not fixed. It depends on the number of records returned)
The basic idea is to get all results based on a set condition and get a random result from these.
Any ideas? Thanks.
Your question seems unclear. However here's a guess:
You want to select the record in the middle:
$count = mysql_num_rows($result);
$middle_name = mysql_result($result, intval($count/2), 'name');
Besides that, you can also do that if you have really less records:
$rs = array();
while ($row = mysql_fetch_assoc($result)){
$rs[] = $row;
}
and then you can use $rs[N-1] to reach Nth record.
Read mysql_data_seek from PHP Manual if you will fetch just one record.
The basic idea is to get all results based on a set condition and get a random result from these.
SELECT ... ORDER BY RAND() LIMIT 1
I know this is not best practice, but as the given information is rather sparse, this could be starting point for further reading. And to be honest, in an small enough application, this is often the easiest solution.
I'm learning currently php/mysql and I'm confused about this bit.
After some heads scratching I have figured out that mysql_fetch_array remembers which row it last accessed and accesses the next one. (I was originally trying to work out how the code was communicating this to it in example code)
so for database:
parent | job
-------+-------------
mom | receptionist
-------+-------------
dad | taxi driver
the code
mysql_fetch_array($result)[job]
returns 'receptionist' the first time and 'taxi driver' the second.
Where/how is it keeping track of this?
What happens if I don't want to access them in order?
thanks
internal implementation in PHP. Don't try to figure it out ;)
if you want a different order, then specify it in your database query.
Where/how is it keeping track of this?
The mySQL server has an internal result pointer. In some databases / wrappers / libraries you can rewind that pointer, but as far as I know, this is not possible in the mysql_* library of functions.
What happens if I don't want to access them in order?
You have to access them in some order. The only alternative to that is to fetch all rows into an array: Then you can access each row randomly.
If you want to change the order of records, do that in the query using the ORDER clause.
Some database wrappers like PDO have a fetchAll() method that does exactly that. For large result sets, this can be memory intensive and break the script's memory limit, which is why it's usually not done this way.
There is another way to attack this question.
If you want to know how YOU TOO can make functions that do what this one does. Here is how:
<?php
function count_off()
{
static $count = 1;
echo $count++;
}
count_off();
count_off();
count_off();
count_off();
count_off();
?>
the above will output 12345
I should mention. You shouldn't do this without a very good reason. It is SUPER hard to trace when debugging.
If you want to access them in a different order, use an ORDER BY clause in your SQL to change the order that the results are retrieved from the database.
The result of mysql_fetch_array is always the next result/row of the query (first the first row off course)
Intern it will keep a pointer how for it has fetched.
If you want to get them in an alternate order, you have to define it in the query.
Like said the result will always be in the order specified by the query (implicit or explicit)
If you wrote typical looking code like this:
$result = mysql_query("SELECT parent, job FROM table");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row['parent'] . ' - ' . $row['job'];
}
Each time mysql_fetch_array() is called, if there is another row in the result, it will return the row as an associative array into the $row variable. Otherwise, it will return false, and the execution of the while loop will end.
Also, because you didn't specify an ORDER BY clause, it defaults to returning rows in the order they were inserted into the table.
The mysql_fetch_array() function grabs one row from the database, in the order that MySQL returns it from the query you gave.
To obtain all the rows, you can put the function in a loop.
while($row = mysql_fetch_array($result)) {
echo $row["job"];
}
This will output:
receptionist
taxi driver
You can change the order by using the sql term order by, which can alphabetically or numerically order your results by a certain column
select * from parent order by job
The above query will order the results alphabetically by the parent job field (results closer to A will come first in the mysql_fetch_*