Reputation: 31
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');
}
?>
Upvotes: 0
Views: 299
Reputation: 74230
You stated in comments that this is your connection:
$con =new mysqli ("local host", "name", "PW", "users")
yet you're using $db
as the variable for $Email
. That should be $con
.
Plus, local host
should be in one word, localhost
.
$con =new mysqli ("localhost", "name", "PW", "users")
while checking for errors for it:
$con =new mysqli ("localhost", "name", "PW", "users");
if ($con->connect_error) {
die('Connect Error (' . $con->connect_errno . ') '
. $con->connect_error);
}
Then these will never work:
$FName = mysql_escape_string($_POST['FirstName']);
$LName = mysql_real_escape_string($_POST['LastName']);
as you are mixing MySQL APIs. Those different APIs/functions do not intermix with each other. You need to use the same from connection to query.
Including:
$Email = $db->real_escape_string($_POST['Email']);
Therefore, this whole block:
$FName = mysql_escape_string($_POST['FirstName']);
$LName = mysql_real_escape_string($_POST['LastName']);
$Email = $db->real_escape_string($_POST['Email']);
needs to be changed to:
$FName = $con->real_escape_string($_POST['FirstName']);
$LName = $con->real_escape_string($_POST['LastName']);
$Email = $con->real_escape_string($_POST['Email']);
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Upvotes: 2