I have been trying to convert my code from MySQL to MySQLi. I am trying to protect from sql injection. I have learned not to use pre_replace. I have been trying the different options as specified in my code below. The only other option that seems to work is the line of code that has mysql_escape_string below. I have tried mysql_real_escape_string and $db->real_escape_string as specified below. However, this causes the website to stop functioning all together. I am not receiving an error message though. I was wondering why the first line of code for $FName works and the following two lines of code won't work. I have spent about 2 hours trying everything I could think of. Sorry if this question is basic but I can't find the answer. Any help would be appreciated.
<?php require "connect.php"; ?>
<?php
if(isset($_POST['Register'])) {
session_start();
$FName = mysql_escape_string($_POST['FirstName']);
$LName = mysql_real_escape_string($_POST['LastName']);
$Email = $db->real_escape_string($_POST['Email']);
$UName = preg_replace('#[^A-Za-z0-9]#i', '', $_POST ["UserName"]);
$PW = preg_replace('#[^A-Za-z0-9]#i', '', $_POST ["Password"]);
$sql = $con->query("INSERT INTO BD (FirstName, LastName, Email, UserName, Password) Values('{$FName}', '{$LName}', '{$Email}', '{$UName}','{$PW}')");
header('Location: login.php');
}
?>
$dbactually a MySQLi connection object? What is present inconnect.php?mysql_real_escape_string()would only be working if you have an active connection to the database. Finally, if your code does nothing, it suggests you do not havedisplay_errorsenabled. Always when developing and testing code, at the top of your script:error_reporting(E_ALL); ini_set('display_errors', 1);and disabledisplay_errorsagain in your live code.mysql_escape_string()works when no connection to the database has been made, which explains that one working. So really, this is down to verifying that whatever connection you attempted to make inconnection.phpis a valid MySQLi object.