I have been using the mysql api in PHP, and am now converting to mysqli for the increased security. The example syntax I have seen uses printf, and I would like to know if this is necessary. At the moment I use echo, like so:
echo '<h1>'.$row['ARTICLE_NAME'].'</h1> <div id='leftlayer' class='leftlayer'> <p><strong>Username: </strong>'.$row['USERNAME'].' <p><strong>Article Number: </strong>'.$row['ARTICLE_NO'].' <p><strong>Subtitle: </strong>'.$row['SUBTITLE'].' <p><strong>Auction Start: </strong>'.$row['ACCESSSTARTS'].' </div>';
Since with mysqli you must bind variables to the result, I have done this like so:
$getRecords->bind_result($ARTICLE_NO, $ARTICLE_NAME, $SUBTITLE$, $CURRENT_BID, $START_PRICE, $BID_COUNT, $QUANT_TOTAL, $QUANT_SOLD, $ACCESSSTARTS, $ACCESSENDS, $ACCESSORIGIN_END, $USERNAME, $BEST_BIDDER_ID, $FINISHED$, $WATCH$$, $BUYITNOW_PRICE, $PIC_URL, $PRIVATE_AUCTION, $AUCTION_TYPE, $ACCESSINSERT_DATE, $ACCESSUPDATE_DATE, $CAT_DESC$, $CAT_PATH, $ARTICLE_DESC, $COUNTRYCODE, $LOCATION$, $CONDITIONS, $REVISED$, $PAYPAL_ACCEPT, $PRE_TERMINATED, $SHIPPING_TO, $FEE_INSERTION, $FEE_FINAL$, $FEE_LISTING, $PIC_XXL$, $PIC_DIASHOW, $PIC_COUNT, $ITEM_SITE_ID);
and would like to know if I could simply replace my reference to $row with the bound variable, for example:
<p><strong>Username: </strong>'.$USERNAME.'
Are there any security problems with this approach, or is it fine
I’m not sure that binding makes your application more secure when you are getting data out of the database, however it will help when you are writing into the DB as you will have no risk of SQL injection.
Whatever approach you take to reading from the DB, you still need to escape the output using
htmlspecialchars()if you are not entirely certain that the data is completely clean. The bound statement will not handle this as you suggest in your comment to Ionut – you have to escape the data in a way that is applicable to where you are outputting it. PHP/MySQL doesn’t know whether you are printing into an HTML document/shell command/json/etc. There isn’t an magic escape method that makes any data safe for any output medium.