I’m a newbie to programming and know only procedural PHP. I’ve been studying prepared statements and other safety issues. I have a few questions about my code below:
I have a table of Footwear sizes that have an identical size and sizeid (e.g. SIZE: 9.5 = sizeID: also 9.5).
My processing file checking then retrieving selected size from a previous html form page.
<?php
$link = mysqli_connect("servert", "user", "passW", "footwear");
if(!$link){
printf("Can't connect to the locatlhost. Errorcode: %d\n", mysqli_connect_errno());
}
if (!mysqli_select_db($link, "footwear")) {
printf("Can't connect to Database. Errorcode: %d\n", mysqli_connect_errno());
}
$stmt = mysqli_stmt_init($link);
if($stmt=mysqli_prepare($link,"SELECT `sizeid`,`size` FROM `size` WHERE `sizeid`"))
{
mysqli_stmt_bind_param($stmt,"i", $sizeid);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt,$sizeid, $size);
mysqli_stmt_fetch($stmt);
if(!floatval($size)) {
echo "Invalid size. Pick another one.";
}
else {
$size = mysqli_real_escape_string($link, $size);
$sizeid= mysqli_real_escape_string($link, $sizeid);
$size= htmlspecialchars($size, ENT_QUOTES, 'UTF-8');
$sizeid= htmlspecialchars($sizeid, ENT_QUOTES, 'UTF-8');
$size = sprintf('%01.1f', $size);
$sizeid = sprintf('%01.1f', $sizeid);
echo " Size: $size";
}
}
?>
The code works but I want to better understand how it does.
1. Is this line (I followed PHP.NET) necessary/critical?:
$stmt = mysqli_stmt_init($link);
Apparently the code works just fine when I omit it and go directly to the query:
$stmt=mysqli_prepare($link,"SELECT `sizeid`,`size` FROM `size` WHERE `sizeid`");
2. From what I’ve read, my understanding is that question marks (?) are used as place holders which are then bound in mysqli_stmt_bind_param ; but when I try
if($stmt=mysqli_prepare($link,"SELECT `sizeid`,`size` FROM `size` WHERE `?`"))…
mysqli_stmt_bind_param($stmt,"i", $sizeid);
it does not work.
Isn’t the idea to “hide” the variable?
3. Is it ok or does it hurt to have mysqli_real_escape_string and htmlspecialchars together. If not why and if it’s alright, should one be called out before the other, if that makes any difference?
4. I need the size to output as a float since real world shoe sizes are so( i.e. 7.5, 9.5, etc.)
Is there any danger in the method I’ve chosen to do so (floatval and sprint)?
mysqli_stmt_initcreates a prepared statement object.mysqli_prepareassigns a query to it. You’re supposed to pass$stmttomysqli_preparemysqli_stmt_bind_paramis used to pass the values to replace the?withPHP Docs: http://www.php.net/manual/en/mysqli-stmt.prepare.php
mysqli_real_escape_stringis only used to escape values before inserting them into the database. Your prepared statements do this for you, somysqli_real_escape_stringis not needed here at all.htmlspecialcharsis used to display HTML characters on a webpage, it escapes them so they don’t get parsed by the browser.