In order to prevent SQL injection, I'm converting every character of a string to be inserted in the database into its ASCII value before performing the query. In order to read the value of the string from the database, I'm reversing the operation.
Is this method safe?
<?php
function toDatabase($string){
$split = str_split(htmlspecialchars($string));
$ascii = "";
foreach($split as $letter){
$ascii .= ord($letter).'-';
}
return $ascii;
}
function fromDatabase($string){
$explode = explode("-",$string);
$phrase = "";
foreach($explode as $ascii_char){
$phrase .= chr($ascii_char);
}
return $phrase;
}
$toBeInserted = toDatabase($_POST['comment']);
$connect = mysqli_connect("","","","");
$query = mysqli_query($connect,"INSERT INTO comments(comment) VALUES ('".$toBeInserted."')");
if(!$query){ die('Error!'); }
$fetch_query = mysqli_query($connect,"SELECT comment FROM comments");
if(!$fetch_query){ die('Error!'); }
while($assoc = mysqli_fetch_assoc($fetch_query)){
echo fromDatabase($assoc['comment']).'<hr>';
}
?>