php mysql count column - php

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.

Related

Is it possible to avoid the "AS" parameter when counting total rows of a mysql table? (php)

Now I use this code to count the total rows of a table:
$sql = "SELECT COUNT(*) AS Total FROM MyTable";
$result = mysqli->query($sql);
$numberOfRows = mysqli_fetch_object($result);
$numberOfRows = $numberOfRows->Total;
I've tried to dump different results that I get when I don't use the "AS" parameter in the query and searched around in the internet about it, but despite the many examples I've found none of them shows the code to retrieve directly the result without the "AS" paramenter.
...
From the answers and comments received I've tried these two code blocks that give the expected result:
$sql = "SELECT COUNT(*) FROM MyTable";
$result = mysqli->query($sql);
And then:
With fetch array:
$numberOfRows = $result->fetch_array($result);
$numberOfRows = $numberOfRows[0];
With fetch assoc:
$numberOfRows = $result->fetch_assoc($result);
$numberOfRows = $numberOfRows["COUNT(0)"];
Performance wise I've found the fetch array works slightly better (tried without opcode).
If you don't use AS to assign an alias, the name of the column in the output will be COUNT(*). You should then be able to retrieve it with:
$numberOfRows = $numberOfRows->{"COUNT(*)"}

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.

How to get max(id) of row data MySql

I want to get the maximum id of row data. In my table first column is id then firstname and etc.
this is the sql command I used to get the max(id) of row data.
<?PHP $maxid=$this->db->query("SELECT MAX(id) FROM `emplyee_personal_details`");
print_r( $maxid) ;?>
but it prints bunch of data as it is a array. But I need only the maximam id of row data for validation before data inserting and updating.
How to get the maxid. I use codeigniter framework.
Try this:
$maxid = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row()->maxid;
UPDATE
This will work even if your table is empty (unlike my example above):
$maxid = 0;
$row = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row();
if ($row) {
$maxid = $row->maxid;
}
The problem with using a raw query like "SELECT MAX(id) ..." is it is not abstract and may not work for every SQL engine. I think the active record way to do it is like this:
$this->db->select_max('id');
$query = $this->db->get('emplyee_personal_details');
// Produces: SELECT MAX(id) as age FROM emplyee_personal_details
See: http://ellislab.com/codeigniter/user-guide/database/active_record.html
SELECT id FROM table ORDER BY id DESC LIMIT 1
That will get you the highest id value, and when I read this, "it prints bunch of data as it is a array" I get the sense that what you really want is a part of that array. DB queries always return complex structures like arrays or objects. So if you wanted just the scalar value (the number as an integer) you might use something like this:
$maxid = (int)$maxid['id'];
or like this (if you have an object):
$maxid = (int)$maxid->id;
HTH, ~Ray
Try this,hope it helps,
return $this->db->select_max('id')
->get('your_table_name')
->row()->id;
public function getMaxCategoryId() {
$query = $this->db->query("SELECT category_id+1 AS maxid FROM " . DB_PREFIX . "category ORDER BY category_id DESC LIMIT 1");
return $query->row['maxid'];
}
error undefined index maxid
<?php`$qry = "select max(ID)+1 As ID from records";`
$result = $con->query($qry);
$row = $result->fetch_assoc();`echo "New ID To Enter = ".$row["ID"];?>
After Connection Just Write This Code It Will Work

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);

MYSQL : help with count row function

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.

Categories