MYSQL : help with count row function - php

I need to retrieve the number of rows in my qrec_id in my table tbl_link_qa, which has values in them.
mysql_query("SELECT COUNT(qrec_id) from tbl_link_qa")or die(mysql_error());
But this doesn't seem to give any output.
----updated:
$x=0;
mysql_query("SELECT COUNT * from tbl_link_qa WHERE qrec_id != $x");

This wouldn't give any output because all it's doing is sending the query to the database. It's not actually collecting the results.
You need to assign the result of mysql_query() to a variable.
<?php
if ($result = mysql_query ('select count(*) from wherever;'))
{
$row = mysql_fetch_assoc ($result);
var_dump ($row);
}
else
die ('some error message');
?>

use this query instead to get number of columns with not null values:
SELECT SUM(qrec_id IS NOT NULL) FROM tbl_link_qa
or
SELECT count(*) FROM tbl_link_qa WHERE qrec_id IS NOT NULL
and #Gordon script

You have a full example in the manual page:
http://es.php.net/mysql_query
See example #2.

Related

php mysql count column

I am trying to get the count of users on my site associated with a certain company, but something is wrong with my query. I keep getting 'no result' or a result of array:
$coresults = mysql_query("SELECT COUNT(user_id) FROM ".DB_USERS." WHERE user_company=".$jdata['job_company']."");
$count = mysql_fetch_array($coresults);
I have also tried with PDO with no success
$nRows = $pdo->query('select count(*) from blah')->fetchColumn();
echo $nRows;
mysql_fetch_array returns an array of your executed query. Use mysql_num_rows instead:
$coresults = mysql_query("SELECT user_id FROM ".DB_USERS." WHERE user_company=".$jdata['job_company']."");
$count = mysql_num_rows($coresults);
You can solve this by giving a name to your count field and using mysql_fetch_assoc function:
$coresults = mysql_query("SELECT COUNT(user_id) AS usercount FROM ".DB_USERS." WHERE user_company=".$jdata['job_company']."");
$count = mysql_fetch_assoc($coresults);
And then, you access the field like this:
print ($count['usercount']);
The mysql_fetch_assoc function turns the selected fields into array keys, then you can access them like a simple array.

Number of Rows in MySQL Query

I am using a script that has a different way of doing a mySQL query to what I am used to. It starts with:
$query = $db->query("SELECT * etc ..... ");
then
while ($result = $db->fetchArray($query)) {
with variables shown as $result['a'], $result['b']. etc.
All I want to do is count the rows that are selected by the query, but mysql_num_rows doesn't work on $result.
What can I use instead?
You can use the count function to count the rows
$query = $db->query("SELECT count(*) as count from (SELECT * etc ..... ) as sq ");
$result = $db->fetchArray($query);
echo $result['count'];
You can change the query to:
SELECT count(*) as cnt etc .....
Then read the results back from the query.

Mysqli count returning incorrect number

so i have this
$countsql = <<<SQL
SELECT COUNT(*)
FROM `deathnote`
SQL;
if ($stmt = mysqli_prepare($db, $countsql)) {
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
mysqli_stmt_store_result($stmt);
printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));
}
The output of this is 1.
Now, when i go into PHP admin on my server and run the exact same query i receive the expected outcome of 12.
Can anybody see where i went wrong, or suggest what to do?
Thanks guys!
$res = mysqli_query($db, "SELECT COUNT(*) FROM deathnote");
$row = mysqli_fetch_row($res)
echo "Number of rows: $row[0]\n";
Either use mysqli_stmt_num_rows OR use COUNT(*) don't mix both.
With mysqli_stmt_num_rows Query should be
SELECT *
FROM `deathnote`;
OR
With COUNT(*) Recommend to use this way for better performance and fast execution of code
$res = mysqli_query("SELECT COUNT(*) FROM deathnote");
$row = mysqli_fetch_array($res)
echo $row[0];
You want the value of COUNT(*), not the number of rows -- the number of rows will always be one: a single row, with one column, containing the value of COUNT(*).
you are taking sql count function very wrong here basically its an aggregate function which returns only 1 as you used printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt)); if you want your desired result which you say is 12 then you will can use mysqli_result, mysqli_fetch_array i-e

count columns from sql query

I'm trying to count the number of rows selected from a table by using the count() function. But it always returns either a '2' for every query with a row/rows selected or a '1' for every query with no row selected.
$sql_usb="select item_name from req_item where item_name='USB Dongle'";
$result_usb=mysql_query($sql_usb);
$row_usb=mysql_fetch_array($result_usb);
$sql_router="select item_name from req_item where item_name='Access Point/Router'";
$result_router=mysql_query($sql_router);
$row_router=mysql_fetch_array($result_router);
$sql_laptop="select item_name from req_item where item_name='Laptop'";
$result_laptop=mysql_query($sql_laptop);
$row_laptop=mysql_fetch_array($result_laptop);
$usb_inv=count($row_usb);
$router_inv=count($row_router);
$laptop_inv=count($row_laptop);
$total_inv=$usb_inv+$router_inv+$laptop_inv;
I've also tried adding isset() (i.e. $usb_inv=count(isset($row_usb));)
and mysql_num_rows() (i.e. $usb_inv=mysql_num_rows($row_usb));)
both give a result of 1.
You should use
SELECT COUNT(*) WHERE ....
Check the doc.
If you only need the total, then only 1 sql will be enough.
// please add error handing yourself.
$sql = "select count(*) from req_item where item_name
where item_name in('USB Dongle', 'Access Point/Router', 'Laptop')";
$result = mysql_query($sql);
$row = mysql_fetch_array($result)
$total = $row[0];
You have to use count in you mysql query like this
$SelectQuery = 'select Count(item_name) as [TotalUSB] from req_item where item_name='USB Dongle'
Then you can get the result by
$result = mysql_query($SelectQuery);
$row = mysql_fetch_array($result);
$USBCount = $row['TotalUSB'];
you should have used mysql_num_rows on result set.
like this.
$usb_inv=mysql_num_rows($result_usb);
$router_inv=mysql_num_rows($result_router);
$laptop_inv=mysql_num_rows($result_laptop);
this will give you proper output.
mysql_fetch_array is returning something like
$row[0] = ...;
$row[item_name] = ...;
If you are using count of an array, it will always return a two,
because it return an array with both index and associate key.
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
Despite the wrong usage of mysql_fetch_array,
you probably should just use a single query
$sql ="select item_name from req_item
where item_name in('USB Dongle', 'Access Point/Router', 'Laptop')";
after that,
$count = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
// do something else ...
// to get count for each item name
$count[$row["item_name"]]++;
}
You should use
$usb_inv = mysql_num_rows($result_usb);
instead of
$usb_inv=count($row_usb);

How to get the result of a select count(*) query in PHP?

I have this query to use in PHP:
mysql_query("select count(*) from registeredUsers where email=".$_SESSION["username"]);
When I use echo to print out the result, nothing gets printed. What exactly is the return value from the above statement?
Your code doesn't include any fetch statement. And as another answer notes, you need single quotes around $_SESSION["username"].
$result = mysql_query("select count(*) from registeredUsers where email='{$_SESSION['username']}'");
// Verify it worked
if (!$result) echo mysql_error();
$row = mysql_fetch_row($result);
// Should show you an integer result.
print_r($row);
mysql_query returns a result resource. You can read the result with mysql_result
$res = mysql_query("select count(*) from registeredUsers where email='".mysql_real_escape_string($_SESSION["username"])."'");
echo mysql_result($res,0);
You need single quotes around the session variable in your query
$result = mysql_query("SELECT COUNT(*)
FROM registeredUsers
WHERE email = '".$_SESSION['username']."' ");
The count query will always return a value, which is 0 if no records are returned, or an integer above 0 if records match it.
It should at least be printing out 0, the query you posted means:
Get the number of records where the email address is equal to the session username
This might not make sense, do you mean to do where username = ".$_SESSION["username"] or something similar?
You may want to echo out the query itself to determine that it is returning what you expect.
mysql_query() returns a resource used to get information from the result set. Use a function such as mysql_fetch_array() to retrieve rows from the result set. In this case, there will only be one row.
It should give you the amount of registere users who have the email address that you provide as the parameter to this query. (Might be a check if the given email address is already registered for another user.)
If the email address is not yet registered, an empty field will be returned. (That might be the reason why nothing gets printed out in your case. Try it with an email address that you are certain of to be in the database.)
$resultemp = mysql_query("select count(*) AS count from registeredUsers where email='{$_SESSION['username']}'");
// Verify mySQL Query Rresult
if (!$resultemp) echo mysql_error();
// Convert mySQL Result for PHP
$counter=mysql_fetch_assoc($resultemp);
$counter=$counter['count'];
// Print Total Employees
echo $counter;
You need to use mysql_fetch_array() to return value in a user defined variable. Then have to print the returned value.
$result=mysql_query("select count(*) from registeredUsers where email='{$_SESSION['username']}'")
$COUNT_NUMBER=mysql_fetch_array($result);
echo "<br>1.Count=" .$COUNT_NUMBER[0];
Try casting it to string before echoing it. As an int, 0 will display as an empty string.

Categories