I have a page that is a survey- based on your answers to previous questions shows and hides other questions using jquery (these questions vary with all input types) I have a save function and then a save and submit function – when saving and submitting I need to verify ALL questions that have not been hidden have been answered – in prototyping this with outputs to test the syntax I realized that the massive quantity of mysqli querys I am running slows the page down (could be upward of 300 questions or as short at 10)
what we have below is a query to find out how many questions are assigned to this survey (sid, $surveyid), $qcountup was my way of making the while statement visit every single number between 1 and the highest question number ($qtotal)
we get down to the while statement which is reoperating for every number from 1 – $qtotal) inside the while we run a query to find out if an answer exists for each number in the database (if it was not answered – it wont exist.
again how this is coded currently could mean 300+ mysqli querys (LAG). any suggestions on how to condense this or write it better?
$qquery = "SELECT * FROM question WHERE (sid = ".$surveyid.");";
$qresult = mysqli_query($dbc, $qquery);
$qtotal = mysqli_num_rows($qresult);
$qcountup = 1;
while($qcountup <= $qtotal){
$squery = "SELECT * FROM answers WHERE sid='".$SID."' AND question='".$qcountup."';";
$sresult = mysqli_query($dbc, $squery) or die(mysql_error());
if (mysqli_num_rows($sresult) )
{
echo("<br>row existed");
} else {
echo("<br>row doesn't exist");
}
$qcountup = $qcountup + 1;
}
First of all, since you’re using mysqli, you should be using prepared queries rather than interpolating variables directly into the query strings.
The first query should be:
If you’re only interested in the number, there’s no need to get all the columns. Set
$qtotalto theqtotalcolumn of this result.For the second part, you can use a LEFT JOIN to match questions against answers, and see which answers are missing:
If an answer is missing, a.question will be NULL in that row.
I’m not sure if I should be using $SID or $surveyid there; your original code used both in different queries.