I'm looking to take the values of several select boxes and join them all up into an array to use to form a mySQL query. The array contains the key and value for the WHERE
statements. I'm making the array like this:
var allvars = [];
$('#more_rows').click(function(){
var onevar = $('#first_select option:selected').text();
var twovar = $('#second_select option:selected').text();
allvars.push(onevar + "," + twovar );
});
This ends up giving me an array like this:
["age , 29", "gender, male"]
The question is...how do I get this into PHP to return a count? I'm working with something like this.
jQuery:
$.ajax({
url: 'att_count.php',
type: 'GET',
dataType: 'JSON',
data: {all_att: allvars},
success: function(data) {
//code to display count
}
});
PHP (relevant parts):
$whereAttributes = isset($_GET['all_att'])? "{$_GET['all_att']}" : '';
$whereAttributes = mysql_real_escape_string($whereAttributes);
$sql = "select count(guid) from full_db2 where {$whereAttributes};";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json');
echo json_encode($result);
Of course, this doesn't work and gives me something like this is the error log:
Call to a member function fetchAll() on a non-object in ../att_count.php on line 14
(which is the line in the PHP above starting with $sql
).
I'm sure there are some better ways to do this overall, but it's my first crack at it. The goal is to be able to pass an "unlimited" number of key/value pairs into PHP to return a COUNT for all the records that have that combination of key/value. Assume that all the joins are "AND" for now...so the final query should be something like this using the array above:
SELECT COUNT(guid) FROM full_db2 WHERE age = '25' AND gender = 'male';
Any suggestions on how to fix this using my current code would help and any suggestion on a cleaner, better way to put this query together would be appreciated.