This is the PHP code I have now to get counts from my database:
$hostname = '****';
$username = '****';
$password = '****';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=firstdb", $username, $password);
echo 'Connected to database<br />';
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** some example variables ***/
$firstpara = 'age';
$secondpara = 'marital_status';
$thirdpara = 'gender';
$data = array($firstpara=>55, $secondpara=>'single', $thirdpara=>'male');
/*** prepare the SQL statement ***/
$stmt = $dbh->prepare("SELECT COUNT(guid) FROM full_db2 WHERE {$firstpara} = :{$firstpara} AND {$secondpara} = :{$secondpara} AND {$thirdpara} = :{$thirdpara}");
$stmt->execute($data);
$count =$stmt->fetch();
echo json_encode($count);
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
This successfully gives me JSON containing the count of users in the database that have the attributes set in my variables above ($firstpara, $secondpara, $thirdpara).
Of course, this is all hard-coded and what I want to do is have the user pick from select boxes containing the different attribute options (e.g., marital status, gender) and based on that give them the possible value options in a second select (e.g., single). I'm generating these select boxes dynamically no problem and can store the selections as variables. I can pass them into AJAX to send to the PHP file, but I have no idea how to parse them all together. Something like this to send the variables. var para1 = "male"; //this captured from select value //any more attributes selected
$.ajax({
url: 'all_get_2.php',
type: 'GET',
dataType: 'JSON',
data: {firstpara: para1, secondpara: para2 ,thirdpara: para3},
success: function(data) {
//do something
}
});
And in my PHP I can add lines like this to set variables:
$firstpara = isset($_GET['firstpara'])? "{$_GET['firstpara']}" : '';
$firstpara = mysql_real_escape_string($firstpara);
The problem here is that I don't know how many attributes (e.g., marital status) the user might select. They might use two or ten or some other number. So, my questions are this:
How can I send the data to PHP (securely...so there are no injections possible) just that I can dynamically add the right number of $firstpara
like variables to account for everything that AJAX passed including adding the right number of where clauses into the SQL statement?
I'm guessing there needs to be some sort of for/each loop or similar, but I'm just not familiar enough with PHP to know how to do it.
Any direction would be appreciated.