count columns from sql query - php

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

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.

Retrieve last row in array using end($array)

After doing some research I hear that to retrieve the last row on an array I can use end($arrayname)
However when putting this into my page it does not retrieve the last, but the first in the array.
$query2 = "SELECT * FROM Items";
$resultSet2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC))
{
$lastElement = end($row2);
echo $lastElement;
}
Looping through the array like this will loop through and display every row in the array one after the other:
Agate & Labradorite Necklace.jpgAgate Necklace.jpgAventurine, Citrine and Carnelian Necklace.jpg
However I was under the impression it should simply repeat the last item (Carnelian necklace.jpg) every time
$row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC);
$lastElement = end($row2);
echo $lastElement
This will print the first item in the array. Any ideas what is causing this to happen?
Why to do so much trouble just select the last row in the query as
SELECT * FROM Items order by primary_key desc limit 1
primary_key is the column name of your table which is primary key
You are applying end to $row2, which already represents a row of data. This makes $lastElement be the last column of each row (the while iterates over rows).
It would not make sense to fetch N items just so that you can repeat the last one of them N times (in addition: your SQL query does not specify a sort order, so which item is going to be last is also unknown to you). If you wanted to do something like that you would fetch one item using LIMIT 1 and the number N using an appropriate query and finally simply use a for loop.
Try with array_pop function in php
$row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC);
$lastElement = array_pop($row2);
echo $lastElement
you can try this :
$query2 = "SELECT * FROM Items DESC limit 1";
$resultSet2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC))
{
echo $lastElement = $row2;
}

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

Echo a selected id from MySQL table

I have this
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
This echo's all id's found in the table.
How can I choose to echo only a selected id.
Say the second id found on the table?
EDIT
I think I have confused people and myself aswell.
Let me try to explain again.
Using the above query I can echo all results found in the table with echo $row['id'];
However I do not want echo all results, just selected ones.
You guys have suggested I use limit or a Where clause.
If I do this I will be limited to just one record. This is not what I want.
I want to echo a selection of records.
Something likes this
echo $row['id'][5], $row['id'][6], $row['id'][6]
But obviously this is incorrect syntax and will not work but hopefully you get what I am trying to do.
Thanks
If you only want the second row then you could change your query to use offset and limit e.g.
SELECT id FROM table LIMIT 1, 1
You could also use a for loop instead of the while loop and then put in a conditional.
UPDATE
Just noticed comments above - you also need to sort the PHP bug by changing mysql_fetch_array to mysql_fetch_assoc.
UPDATE 2
Ok based on your update above you are looking to get all of the rows into an array which you can then iterate over.
You can just use mysql_fetch_array and then use $array[0]. For example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row[0];
}
From what I can gather from your questions you should not be selecting all records in the table if you wish to just use the Nth value, use:
SELECT id FROM table LIMIT N, 1
That will select the Nth value that was returned. Note: The first result is 0 so if you wish to get the second value the Nth value should be 1.
mysql_data_seek() let's you jump to a specific data-set(e.g. the 2.nd)
Example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
//get the 2nd id(counting starts at 0)
if(mysql_data_seek($result,1))
{
$row=mysql_fetch_assoc($result);
echo $row['id'];
}
OR:
use mysqli_result::fetch_all
It returns an array instead of a resultset, so you can handle it like an array and select single items directly (requires PHP5.3)

Read data from all rows in column PHP MySQL

I am doing some work that requires me to add the data from a specific column, say Column 1, to a PHP array. I can get the data from the first row in Column 1, but it stop there. How do I collect that columns data from every row in the table?
You have to loop over the result set in a while loop:
$result = mysql_query('SELECT...');
$data = array();
while(($row = mysql_fetch_array($result))) {
$data[] = $row['columnName'];
}
Every call to mysql_fetch_array will get the next row of the result set. If there is no row anymore, it will return null and the loop stops.
The documentation provides good examples.
Update:
Regarding duplicates: Either specify your SQL query correctly (preferred), e.g.
SELECT DISTINCT columnName FROM table
or use array_unique after you fetched all the data:
$data = array_unique($data);
//Variable declaration as a small sql query
$query = "select RowName FROM Table;";
//Execute Query
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
//Do Stuff
}

Categories