Jump to content

Recommended Posts

I am having a hard time getting the right syntax with count using 2 tables.

 

Here's what I have

$query = "SELECT COUNT(*) as num FROM people, constructs INNER JOIN people ON (people.id = constructs .pt_id) WHERE constructs .signstat = 'y' ";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];

 

 

but I get: warning mysql_fetch_array(); supplied argument is not a valid mysql result resource

Link to comment
https://forums.phpfreaks.com/topic/229913-using-count-with-inner-join/
Share on other sites

You seem to have joined the people table twice. Try this:

 

$query = "SELECT COUNT(*) as num 
FROM constructs INNER JOIN people ON (people.id = constructs.pt_id) 
WHERE constructs.signstat = 'y' ";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];

 

Although I don't recommend combining the fetch and query in a single call. The error message indicates that mysql_query() failed and with it embedded in the call to mysql_fetch_array() you can't catch it and take action. Also, you are trying to reference the field name in the $total_pages array, but you fetched it as a numeric array. I would rewrite the whole thing like this:

 

$query = "SELECT COUNT(*) as num 
FROM constructs INNER JOIN people ON (people.id = constructs.pt_id) 
WHERE constructs.signstat = 'y' ";
$res = mysql_query($query);
if ($res === false) {
  // In development output some stuff to help fix the problem
  // But don't leave this in production
  die(mysql_error() . PHP_EOL . 'SQL: ' . $query);
}
$total_pages = mysql_fetch_assoc($res);  // Use fetch_assoc() so we get the column names as array keys
$total_pages = $total_pages['num'];  // num is a string, it needs to be in quotes

 

EDIT: Apparently mysql_fetch_array() returns the data with both numeric indexes and column name indexes. I still recommend using mysql_fetch_assoc() specifically; but, to each his own.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.