I am hoping somebody can help me. I have been reading up on how to prevent sql injections and I am still confused about difference between mysqli "object oriented" & "prepared statements". The thing is I am lost as to whether or not "object oriented mysqli" alone is good enough to prevent against mysql injection attacks. For example is this code below which is object oriented secure enough against all sql injections or at least as secure as a prepared statement?:

function cCnx()
{
$bgCnx = new mysqli("localhost", "root", "", "test");

if (mysqli_connect_errno())
{
echo "Error ". mysqli_connect_error();
exit();
}
else
{
return $bgCnx;
}
}

function cGet_Countries()
{
$cnx_am = cCnx();
$query = "SELECT FULLNAME,CC1 FROM countries WHERE CC1 != 'US' and CC1 != 'CA' ORDER BY FULLNAME";
$result = $cnx_am->query($query);
$countries[0]['num'] = $result->num_rows;
$i = 1;
while($result2=$result->fetch_array())
{
$countries[$i]['name'] = $result2['FULLNAME'];
$countries[$i]['cod'] = $result2['CC1'];
$i++;

}
return $countries;
}

I hope you can help me understand as I am lost on this and I just want to make sure that when I am coding the site from the beginning that I am doing it in the safest most efficient way to prevent sql injections as well as optimize speed for end users.

Thanks,
Will

    The correct contrast is between the object oriented and procedural interface. Prepared statements can be used in both cases. As it stands, your code is not vulnerable to SQL injection since no incoming variables are used. If incoming variables were used, you should use prepared statements, or if that is not feasible, then use mysqli::real_escape_string().

      Write a Reply...