Preventing SQL injection by converting all characters to their ASCII values 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?

&lt;?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']).'&lt;hr&gt;';
}
?&gt;
There's a common credo believed when evaluating the security of software:

If it's homemade, it's unlikely secure.

Sec.SE has a Q&amp;A about homemade algorithms, which is somewhat germane to your circumstance.

I suggest you look into preparing your queries, as that would be your best action to take in this situation. It's essentially what you're trying to do anyways. Again, the PHP docs contain more information on mysqli::prepare.

I just noticed your comment to Mat's Mug, and prepared queries will not reach the database twice as you've said. When they're implemented correctly, they will be 100% secure (in doing their job, you might have to protect against other faults).

If you're worried about performance or efficiency, you might find the following select quotes helpful:


  Prepare is followed by execute. During execute the client binds parameter values and sends them to the server.


The database is not reached twice.


  A prepared statement can be executed repeatedly. Upon every execution the current value of the bound variable is evaluated and sent to the server. The statement is not parsed again. The statement template is not transferred to the server again.


I know you said it's only a single query per page, but things change in the future, and it's better to know you'll be safe then too.


  Prepared statements are using the so called binary protocol. The MySQL server sends result set data "as is" in binary format. Results are not serialized into strings before sending. The client libraries do not receive strings only. Instead, they will receive binary data and try to convert the values into appropriate PHP data types.


If you happen to be curious as to how and why paramterized queries are so much safer!

These quotes are from the PHP manual on prepared statements.