2
\$\begingroup\$

I wanted to know if this code is safe against SQL injection or not? Also do I need to mysqli_close if I already did the mysqli_stmt_close? Other suggestions are always welcome.

if ($stmt = mysqli_prepare($connect, "SELECT subcategories.subcat_name, subsubcategories.subsubcat_name, subcategories.subcat_ID FROM subcategories INNER JOIN subsubcategories ON subcategories.subcat_ID=subsubcategories.subcat_ID WHERE subcategories.cat_ID = ? OR subcategories.extra_cat_ID = ? ORDER BY subcategories.subcat_name, subsubcategories.subsubcat_name ASC")){
mysqli_stmt_bind_param($stmt, "ii", $cat_ID, $cat_ID);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $subcat_name, $subsubcat_name, $subcat_ID);
$lastcat = 0;
while (mysqli_stmt_fetch($stmt)){
    if($lastcat != $subcat_ID){
        $lastcat = $subcat_ID;
        echo "<br>"; 
        echo $subcat_name;
        echo "<br>";
        echo "<br>";
        }

    echo $subsubcat_name;
    echo "<br>";
    }
}
mysqli_stmt_close($stmt);
mysqli_close($connect);
\$\endgroup\$
  • \$\begingroup\$ This seems like a practice project, but as soon as your projects get larger, you're going to want to separate the database and the presentation of the application. That would mean moving the echo "<br>";s away from the database connecting code. \$\endgroup\$ – Alex L Jun 12 '14 at 21:20
1
\$\begingroup\$

SQL Injection

Yes, your code is safe against SQL Injection. Make sure to use prepared statements when fetching things from the database as well, even in internal application services without user input.

Others

Well, I'm guessing this is a subset of the code in Displaying categories and subcategories in php having different tables, so my review there still stands.

\$\endgroup\$
  • \$\begingroup\$ @ Madara Uchiha Yes it is. This subquestion was deleted there so I asked the question in a new post. Thanks Madara. \$\endgroup\$ – Thoaren Jun 12 '14 at 10:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.