I have the following PHP function:
public function signup() {
$mysql = mysqli_connect(HOSTNAME, USERNAME, PASSWORD, DATABASE);
if (mysqli_connect_errno($mysql)) {
$this->viewModel->set("pageTitle", "Signup");
$this->viewModel->set("message", "There was an error connecting to the server.");
return $this->viewModel;
}
if ($result = $mysql->query("SELECT id FROM mailinglist WHERE email='" . $this->email . "';")) {
if ($result->num_rows == 0) {
$mysql->query("INSERT INTO mailinglist (email) VALUES ('" . $this->email . "');");
$this->viewModel->set("message", "Great! Thanks for signing up " . $this->email . ".");
} else {
$this->viewModel->set("message", "You are already signed up for updates!");
}
} else {
$this->viewModel->set("message", "There was an error adding you the mailing list.");
}
$this->viewModel->set("pageTitle", "Signup");
return $this->viewModel;
}
Which runs fine and returns exactly what I want, however, if I try to use mysqli_real_escape_string() to my queries, it doesn't work. That is, the following code
public function signup() {
$mysql = mysqli_connect(HOSTNAME, USERNAME, PASSWORD, DATABASE);
if (mysqli_connect_errno($mysql)) {
$this->viewModel->set("pageTitle", "Signup");
$this->viewModel->set("message", "There was an error connecting to the server.");
return $this->viewModel;
}
$query = $mysql->real_escape_string("SELECT id FROM mailinglist WHERE email='" . $this->email . "';");
if ($result = $mysql->query($query)) {
if ($result->num_rows == 0) {
$query = $mysql->real_escape_string("INSERT INTO mailinglist (email) VALUES ('" . $this->email . "');");
$mysql->query($query);
$this->viewModel->set("message", "Great! Thanks for signing up " . $this->email . ".");
} else {
$this->viewModel->set("message", "You are already signed up for updates!");
}
} else {
$this->viewModel->set("message", "There was an error adding you the mailing list.");
}
$this->viewModel->set("pageTitle", "Signup");
return $this->viewModel;
}
does not work. It is not a problem with the connection and I have tried using mysqli_real_escape_string() instead of $mysql->real_escape_string() but neither of them work. Can anyone see what is wrong with this code?
real_escape_stringescapes data for use in a query; it doesn’t magically render a query you’ve already thrown arbitrary input into safe. But it doesn’t really matter what it does, because since you’re using MySQLi, you can use and should be using prepared statements.