473,800 Members | 2,383 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

MySql count

The following snippet (for whatever reason) returns no value for the
count. Suggestions?
$arr = array ("A", "B", "C", "D", "E");
foreach ($arr as $client) {
$count = mysql_query('SE LECT COUNT(*) from table where columnA =
$client');
echo "$client has $count";
echo '<br>';
}

Nov 20 '06 #1
9 2737
Akhenaten wrote:
The following snippet (for whatever reason) returns no value for the
count. Suggestions?
$arr = array ("A", "B", "C", "D", "E");
foreach ($arr as $client) {
$count = mysql_query('SE LECT COUNT(*) from table where columnA =
$client');
echo "$client has $count";
echo '<br>';
}

1. You can't pass variables within single quotes.

Instead of '... $client' you either need "... $client" or '... '.$client

2. Strings in MySQL queries need to be surrounded by quotes (either single or
double).

This will work:

"SELECT COUNT(*) from table where columnA = '$client'"

as will this:

'SELECT COUNT(*) from table where columnA = "'.$client. '"'

--
Christoph Burschka
Nov 20 '06 #2
..oO(Christoph Burschka)
>Akhenaten wrote:
>The following snippet (for whatever reason) returns no value for the
count. Suggestions?
[...]

1. You can't pass variables within single quotes.
[...]

2. Strings in MySQL queries need to be surrounded by quotes (either single or
double).
[...]
3. mysql_query() just returns a resource ID. You have to use one of the
mysql_fetch_* functions to get the actual results.

Micha
Nov 20 '06 #3
On Mon, 20 Nov 2006 18:48:39 +0100, Michael Fesser <ne*****@gmx.de wrote:
>.oO(Christop h Burschka)
>>Akhenaten wrote:
>>The following snippet (for whatever reason) returns no value for the
count. Suggestions?
[...]

1. You can't pass variables within single quotes.
[...]

2. Strings in MySQL queries need to be surrounded by quotes (either single or
double).
[...]

3. mysql_query() just returns a resource ID. You have to use one of the
mysql_fetch_ * functions to get the actual results.
4. Always check for errors, as the database can tell you what went wrong via
mysql_error().

--
Andy Hassall :: an**@andyh.co.u k :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool
Nov 20 '06 #4
Actually fixed it using the following:

$arr = array ("A", "B", "C", "D", "E");
foreach ($arr as $client) {
$query = mysql_query("SE LECT * from table where columnA = '$client' ");
$num_rows = mysql_num_rows( $query);
echo "$client has $num_rows";
echo '<br>';
Unsure as why but for whatever reason I simply can't get a value using
count <pounding head on keyboard>.

On Nov 20, 11:32 am, Christoph Burschka
<christoph.burs c...@rwth-aachen.dewrote:
Akhenaten wrote:
The following snippet (for whatever reason) returns no value for the
count. Suggestions?
$arr = array ("A", "B", "C", "D", "E");
foreach ($arr as $client) {
$count = mysql_query('SE LECT COUNT(*) from table where columnA =
$client');
echo "$client has $count";
echo '<br>';
}1. You can't pass variables within single quotes.

Instead of '... $client' you either need "... $client" or '... '.$client

2. Strings in MySQL queries need to be surrounded by quotes (either single or
double).

This will work:

"SELECT COUNT(*) from table where columnA = '$client'"

as will this:

'SELECT COUNT(*) from table where columnA = "'.$client. '"'

--
Christoph Burschka
Nov 20 '06 #5
Akhenaten wrote:
The following snippet (for whatever reason) returns no value for the
count. Suggestions?
$arr = array ("A", "B", "C", "D", "E");
foreach ($arr as $client) {
$count = mysql_query('SE LECT COUNT(*) from table where columnA =
$client');
echo "$client has $count";
echo '<br>';
}
I see no single-quotes around $client in the SELECT
query.
That would make "$client" seem to be a field or
variable name, instead of a string value.

That probably means you're querying for where
columnA = the value of a variable named "$client"
instead of what you meant to query for which was
where columnA = the string in "$client".

I do that so much - it's one of the first errors I
check for anymore!
Nov 20 '06 #6
..oO(Akhenaten)
>Actually fixed it using the following:

$arr = array ("A", "B", "C", "D", "E");
foreach ($arr as $client) {
$query = mysql_query("SE LECT * from table where columnA = '$client' ");
$num_rows = mysql_num_rows( $query);
echo "$client has $num_rows";
echo '<br>';
Unsure as why but for whatever reason I simply can't get a value using
count <pounding head on keyboard>.
As said, it requires a mysql_fetch_* function to get the results from a
query. Your "fix" above is just an ugly hack. Additionally with some
more SQL and a GROUP BY clause you could drop the foreach loop and do it
all with a single query, something like

SELECT columnA, COUNT(*) AS count
FROM table
WHERE columnA IN ('A', 'B', 'C', 'D', 'E')
GROUP BY columnA
ORDER BY columnA

Micha
Nov 20 '06 #7
Andy Hassall wrote:
On Mon, 20 Nov 2006 18:48:39 +0100, Michael Fesser <ne*****@gmx.de wrote:
>>.oO(Christo ph Burschka)
>>>Akhenaten wrote:
The following snippet (for whatever reason) returns no value for the
count. Suggestions?
[...]
code re-inserted
>>>$arr = array ("A", "B", "C", "D", "E");
foreach ($arr as $client) {
$count = mysql_query('SE LECT COUNT(*) from table where columnA =
$client');
echo "$client has $count";
echo '<br>';
}
>>1. You can't pass variables within single quotes.

2. Strings in MySQL queries need to be surrounded by quotes

3. mysql_query() just returns a resource ID.

4. Always check for errors,
5. Indent your code. Always. Even for a very small example posted to
usenet.

--
I (almost) never check the dodgeit address.
If you *really* need to mail me, use the address in the Reply-To
header with a message in *plain* *text* *without* *attachments*.
Nov 20 '06 #8
Michael Fesser wrote:
.oO(Akhenaten)
>Actually fixed it using the following:

$arr = array ("A", "B", "C", "D", "E");
foreach ($arr as $client) {
$query = mysql_query("SE LECT * from table where columnA = '$client' ");
$num_rows = mysql_num_rows( $query);
echo "$client has $num_rows";
echo '<br>';
Unsure as why but for whatever reason I simply can't get a value using
count <pounding head on keyboard>.

As said, it requires a mysql_fetch_* function to get the results from a
query. Your "fix" above is just an ugly hack. Additionally with some
more SQL and a GROUP BY clause you could drop the foreach loop and do it
all with a single query, something like

SELECT columnA, COUNT(*) AS count
FROM table
WHERE columnA IN ('A', 'B', 'C', 'D', 'E')
GROUP BY columnA
ORDER BY columnA

Micha
And since one of the bottle-necks in a web application is the time it takes for
the database to process the query and return the result set, it makes sense to
minimize the number of queries. The above is the best way to go. Use it in this
code:

$sql = "...[shown above]";
$res = mysql_query($sq l);
$counts=array() ;
while ($row=mysql_fet ch_array($res)) $counts[$row['columnA']]=$row['count'];

in the end, $counts will be an array containing all the letters as keys and the
associated counts as values.

--
Christoph Burschka
Nov 20 '06 #9
I created a function get_query_rows( ) that makes the repetitive task of
using mysql_query() and looping through abnd getting the results easier
(for me anyhow).
$arr = array ("A", "B", "C", "D", "E");
foreach ($arr as $client)
{
$query = 'SELECT COUNT(*) as count from table where columnA =
"'.$client. '"';
$rows = get_query_rows( $query);
$count = $rows[0]['count'];
echo "$client has $count<BR />";
}

function get_query_rows( $query,$resourc e=null)
{
$rows = false;
$result = ( $resource )
? @mysql_query($q uery,$resource)
: @mysql_query($q uery);
if ( $result )
{
$rows = array();
$num_rows = mysql_num_rows( $result);
for ( $i=0; $i<$num_rows; $i++ )
$rows[] = mysql_fetch_ass oc($result);
}
else
trigger_error(m ysql_error());
return $rows;
}

Nov 20 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
5008
by: Fatt Shin | last post by:
Hi, I'm running MySQL 4.0.13, connecting from PowerBuilder 9 using ODCB Connector 3.51. I'm facing a problem where whenever I issue a SELECT COUNT(*) statement from PowerBuilder, I always get SQL syntax error back from MySQL. (Refer to ODBC Trace I captured below). metrohouse af8-b94 ENTER SQLExecDirect HSTMT 014D2360 UCHAR * 0x020A0EA2 "select count ( *) from code
0
2691
by: Philip Stoev | last post by:
Hi all, Please tell me if any of this makes sense. Any pointers to relevant projects/articles will be much appreciated. Philip Stoev http://www.stoev.org/pivot/manifest.htm ===================================
0
3950
by: Mike Chirico | last post by:
Interesting Things to Know about MySQL Mike Chirico (mchirico@users.sourceforge.net) Copyright (GPU Free Documentation License) 2004 Last Updated: Mon Jun 7 10:37:28 EDT 2004 The latest version of this document can be found at: http://prdownloads.sourceforge.net/souptonuts/README_mysql.txt?download
4
9717
by: Ross Contino | last post by:
Hello to all: I have been searching the web for examples on how to determine a median value in a mySQL table. I have reviewed the article at http://mysql.progen.com.tr/doc/en/Group_by_functions.html. I am an experienced VB programmer that has recently moved to PHP/mySQL. My employer has a text file outputted from a vendor specific software with data. However it cannot be manipulated because it is text. I created a web that reads the...
7
2290
by: Schraalhans Keukenmeester | last post by:
X-Followup: comp.lang.php I have a PHP script that adds messages to a simple MySQL Database. (PHP 5.0.3, MySQL 4.1.1) One of the fields it stores is msgid. The new msgid is a count of all current msgs in the db plus one $query = 'select count(*) from messagesdb;'; $result = mysql_query ($query, $conn);
1
3383
by: jlee | last post by:
I'm pretty much a newbie on mysql, and I need some help. I am running mysql Ver 12.22 Distrib 4.0.24, for portbld-freebsd5.4 (i386) on a server hosting an active website. The site's developer uses his own php shopping cart to receive customer orders. The configuration was done via cPanel with no external modifications - which produced no protests when built, ran and connected with no
3
13957
by: auron | last post by:
Hi there, I have a really stupid and banal problem with showing the results of a MySQL query in PHP, preciselly with MySQL count() function that gives to a variable in PHP the result. NOTE: The problem here is PHP not MySQL, in MySQL everything works just fine. Here is the query that I wrote for getting the number of how much
6
1499
by: ojorus | last post by:
Hi! My company make several flash-based games, and I use php to communicate with mysql to provide highscore-lists. My problem is this: When I save a player's score in the mysql-table, I want to find which place the player got with his score (today). To get this I have tried two different solutions, which both works, but are very ineffective: (The Time-field is a DateTime type, and I have Score and Time as Indexes)
1
15396
by: Ike | last post by:
Recently, I began using a different MySQL verver (i.e. different machine as well as different version#, going from 4.12a to 4.1.9 max). The following query used to work: select firstname, lastname, from associates where username like 'nancianne' but now fails with: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from associates
3
3116
by: Auddog | last post by:
I have the following query that works in mysql: select id, order_no, price, count(item_no), sum(price) from production WHERE item_no = '27714' group by item_no; When I setup my query in php, I use: $query2 = "SELECT id, order_no, price, count(item_no) as count from production where item_no = '27714";
0
9691
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9551
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10253
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10035
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9090
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7580
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4149
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2945
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.