this is my php code
$sql="SELECT * FROM table_name WHERE FROM_UNIXTIME(date, '%Y') = $q order by id desc";
$q = mysql_query($sql) or die(mysql_error().$sql);
$sql1="SELECT * FROM table_name WHERE FROM_UNIXTIME(date, '%Y') = $q";
$query=mysql_query($sql1);
this gathers the results correctly (everything is correct)
but when i use this to calculate the total results it gives me nothing, however i had for example 3 results:
$total = mysql_num_rows($query);
Because your input isn't a query handle... Since you set $q to the query handle, you should be using that in mysql_num_rows():
$total = mysql_num_rows($q);
As I can see $q is resource not a string value, for that reason $sql1 query would fail with error
If you ask for the number of rows before you've actually retrieved the rows, the database may return zero or some intermediate number. This is true for Oracle and MySQL (don't know about MSSQL but I suspect it's the same). From the PHP docs:
Note: If you use mysql_unbuffered_query(), mysql_num_rows()
will not return the correct value until all the rows in the
result set have been retrieved.
Even for a buffered query, PHP would have to fetch all the rows in order to count them.
Related
I have a query which is to check data from two different tables everything is working fine though. When i paste the query in cPanel then result is showing like this
MySQL returned an empty result set (i.e. zero rows). (Query took 0.0005 sec)
but when i count the query in php it is returing 1 instead of 0 don't know why
Here is my Sql query
SELECT mobile, emailid
FROM tbl_users
WHERE mobile =9653878051
AND emailid = 'rawat#gmail.com'
GROUP BY mobile
UNION ALL SELECT mobile, email
FROM tbl_addusr
WHERE mobile =9653878051
AND email = 'rawat#gmail
.com'
LIMIT 0 , 30
and i am counting it like this i am storing the sql result in data variable
$result = mysql_num_rows($data);
echo count($result)>0?1:0;
and it is resulting 1 instead of 0
You do not need to count anything. mysql_num_rows gives you the number of rows.
Use like this:
$result = mysql_query($query);
echo mysql_num_rows($result);
1: Stop using mysql_* functions. Use mysqli or PDO instead.
2: Use SQL Count: http://www.w3schools.com/sql/sql_func_count.asp
Oh yes, just as advise: don't use variable names like $aaaaaa ... names like this one just say nothing about what the variable is and when you repopen the project in a few month you won't understand anything what you've done.
You are using the count() function of PHP, which from the manual states:
Returns the number of elements in array_or_countable. If the parameter is not an array or not an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable is NULL, 0 will be returned.
So on your case, it will return 1. Just remove the count() function and compare the value of $result itself in your ternary operator.
mysql_num_rows — Get number of rows in result not array
Description
int mysql_num_rows ( resource $result )
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
Parameters
result
The result resource that is being evaluated. This result comes from a call to mysql_query().
Return Values
The number of rows in a result set on success or FALSE on failure.
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query(" SELECT mobile, emailid
FROM tbl_users
WHERE mobile =9653878051
AND emailid = 'rawat#gmail.com'
GROUP BY mobile
UNION ALL SELECT mobile, email
FROM tbl_addusr
WHERE mobile =9653878051
AND email = 'rawat#gmail
.com'
LIMIT 0 , 30", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
echo $num_rows>0?1:0;//compare like this
?>
check doc http://php.net/manual/en/function.mysql-num-rows.php and http://php.net/manual/en/function.count.php
If I run a query that returns multiple rows, is there a way I can select just one row out of that result?
So if I do something like
SELECT * FROM table WHERE number = 10
and it returns 33 results, is there a way I can go through those one at a time instead of returning the whole result set at once, or just return, for example, row 5 of the result set?
I have read about scrollable cursors but it seems they don't work on MySQL, although that seems to be what I am looking for....
I am using PDO with MySQL and PHP. I hope this makes sense, if not I will try and explain better.
Edit: This worked for what I wanted. Thanks.
$stmt = $dbh->prepare("SELECT * FROM $table WHERE user_points = '$target' ORDER BY tdate DESC LIMIT $count,1");
is there a way I can select just one row out of that result?
Yes there is, you can use LIMIT:
SELECT * FROM table WHERE number = 10 LIMIT 1;
$sql= "SELECT * FROM $table WHERE user_points = '$target' ORDER BY tdate";
$stmt= $pdo -> prepare($sql);
$stmt->execute();
$data = $stmt ->fetchAll();
//You asked about getting a specific row 5
//rows begin with 0. Now $data2 contains row 5
$data2 = $data[4];
echo $data2['A_column_in_your_table'];//row 5 data
With mysqli I can get the number of rows from a select query by using mysqli_num_rows. I can't find a way to do that with PDO without having to do a separate query like SELECT COUNT(*)? I don't see the point in doing a separate query when I already have a recordset.
You could use SQL_CALC_FOUND_ROWS as documented here. For example:
$result = $db->prepare("SELECT SQL_CALC_FOUND_ROWS id, name FROM fruit WHERE calories > 100");
$result->execute();
$result = $db->prepare("SELECT FOUND_ROWS()");
$result->execute();
$row_count =$result->fetchColumn();
echo $row_count;
This option is normally used to get full match counts when you have a LIMIT clause, however, it works just fine without one, and it's much more efficient than issuing the same query again with a COUNT(*) since it just retrieves the count value stored by the first query value and does not have to run another full query.
In Pdo you use rowCount. Example: $string-> rowCount ();
RTM: http://php.net/manual/en/pdostatement.rowcount.php
For most databases, PDOStatement::rowCount() does not return the
number of rows affected by a SELECT statement. Instead, use
PDO::query() to issue a SELECT COUNT(*) statement with the same
predicates as your intended SELECT statement, then use
PDOStatement::fetchColumn() to retrieve the number of rows that will
be returned. Your application can then perform the correct action.
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* .... */
I don't want to copy the whole PHP.net page, please just read it.
Why does PDO not have num_rows ?
You may think it's slower to have 2 queries but it isn't. PDO is a general client library for several database systems, not only MySQL. For performance reasons, not everys database system has internal, technical ability to calculate the total rows in select uppon the query. Knowing the total number of rows requires to examine all rows before serving them.
try this:
$sql = "SELECT count(id) FROM `table` WHERE condition";
$result = $db->prepare($sql);
$result->execute();
$row_count =$result->fetchColumn();
echo $row_count;
It was some time ago I worked with PHP, MySQL and SQL, so I need some help. In my table I have 44 rows, but I only want to get 24 of them. Before I have just loaded all the rows like in the code below, and now I need some help to modify it to only load 24 rows. Thanks!
$query = "SELECT * FROM {$tableObject} {$sort1};";
$res = $mysqli->query($query);
$row_cnt = mysqli_num_rows($res);
while($row01 = $res->fetch_object()) {
// Some other code here
}
Use this in your query:
LIMIT 24
LIMIT is a MySQL function that selects a particular range of results from your query results. There are basically two ways of using it:
By simply specifying the number of results you want to fetch, like LIMIT 24; or
By specifying another range in the form of LIMIT X, Y. Where X is the beginning and Y is number of rows you want to fetch, like: LIMIT 10,5 that would select the 5 results from row 11 to 15
In your particular case you can simply replace this line:
$query = "SELECT * FROM {$tableObject} {$sort1};";
For:
$query = "SELECT * FROM {$tableObject} {$sort1} LIMIT 24;";
or even:
$query = "SELECT * FROM {$tableObject} {$sort1} LIMIT 0,24;";
For a better understanding about how to use limit, I recommend you to read this page from MySQL manual
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Whats the best way to get total # of records in a mysql table with php?
When i run :
mysql_query("SELECT COUNT(col) FROM table");
I end up with something like this :
(Resource) mysql result #4
How can i only get an integer that represent the number of row in my table so that later i can use it to make a simpel check such as : $result < 10.
Many Thanks
You have two options.
Get the result from the resource returned by the count query:
$resource = mysql_query("SELECT COUNT(col) FROM table");
$count = mysql_result($resource,0);
Or, get the number of rows from the resource returned by the query (without count).
$resource = mysql_query("SELECT col FROM table WHERE col IS NOT NULL");
$count = mysql_num_rows($resource);
I would recommend that you use the first, the reason being is that it is unnecessary to extract all the data from the table when you only need the count.
Note I've added WHERE col IS NOT NULL on the second one in order to recreate the effect of count(col) as opposed to count(*), as it will only count the non-null values of col.
mysql_query returns a mysql resource. To get the query output use:
$result = mysql_query("SELECT COUNT(col) FROM table");
if (!$result) {
die('Error:' . mysql_error());
}
echo mysql_result($result, 0);
See more examples here: http://php.net/manual/en/function.mysql-query.php
EDIT
By the way, this will only count the number of rows with a non-null value in col. To get the total number of rows in the table, use count(*)
Two options.
SELECT COUNT(*)....
Do the normal query. And add this line after retrieving the resource.
$num = mysql_num_rows($resource);