Search code examples
phphtmlhref

Right format for query


I am making a test program in which I need to use this code:

"href=\"testmng.php?manageqn=" . htmlspecialchars_decode($r['testname'], ENT_QUOTES) . "?subjectname=". htmlspecialchars_decode($r['subname'], ENT_QUOTES)

My question is what is the right format when manageqn and subjectname have the right values:

else if ((isset($_REQUEST['manageqn'])) && (isset($_REQUEST['subjectname']))) {

$testname = $_REQUEST['manageqn'];
$subname = $_REQUEST['subjectname'];
$result = executeQuery("select testid from test where testname='" . htmlspecialchars($testname, ENT_QUOTES) . "';");

if ($r = mysql_fetch_array($result)) {
    $_SESSION['testname'] = $testname;
    $_SESSION['subjectname'] = $subname;
    $_SESSION['testqn'] = $r['testid'];

    header('Location: prepqn.php');
}
}

Solution

  • Assuming you're using mysqli to connect to the database, you need to escape the string using the myqli_real_escape_string() PHP function, otherwise you risk adding sql injection to your application:

    executeQuery("select testid from test where testname='" . myqli_real_escape_string($testname) . "';");
    

    I'd recommend however to switch to a parametrized query approach, by using the prepared statements feature that mysqli provides. You can then have executeQuery() like this:

    executeQuery("select testid from test where testname=?", $testname)
    

    no need to escape strings in order to have a safe query.

    If you're using the deprecated mysql driver, then you should use mysql_real_escape_string().