Reputation: 1883
Can anyone help. I'm trying to shore up my security using mysql_real_escape_string on values passed to PHP for an internal messaging service, but I must be getting the syntax wrong somewhere because the values are not being inserted into the database. I've looked around for tutorials, help etc but struggling to get it right.
The code I'm using is below. The values that haven't been escaped ($email, $from, $time) are being entered correctly, but the other values are just entered blank.
<?php
session_start();
$conn = mysqli_connect('localhost', 'username', 'password', 'dbname');
$email=$_SESSION['email'];
$to = $_POST ['touser'];
$toemail = $_POST['touseremail'];
$from = $_SESSION['name'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$time = time();
$query ="INSERT INTO messages
(to_user, to_email, subject, message, from_user, from_email, daterecord)
VALUES (
'" . mysql_real_escape_string($conn, $to) . "',
'" . mysql_real_escape_string($conn, $toemail) . "',
'" . mysql_real_escape_string($conn, $subject) . "',
'" . mysql_real_escape_string($conn, $message) . "',
'$from', '$email', '$time')";
$send = $conn -> query($query);
echo "Message sent!";
?>
Upvotes: 0
Views: 170
Reputation: 168655
The actual problem you're having is that you're mixing up between the mysql
extension and the mysqli
extension.
If you're using mysqli_connect()
, then all the DB functions you use must begin mysqli_
.
You're using mysql_real_escape_string
, when the function you actually want is mysqli_real_escape_string
.
That i
is very important.
However, if you'll allow me to go beyond the actual problem described, I would recommend moving away from escaped queries, and instead use Parameterised Queries.
Parameterised Queries is a technique that allows you to specify queries like this:
SELECT fieldname from talbe WHERE arg = ? AND arg2 = ?
and then replace those ?
s with your variables using mysqli_bind_param()
.
This technique is considered a much better technique than using escape strings.
Hope that helps.
Upvotes: 0
Reputation: 11117
Use the function mysqli_real_escape_string() instead
Doc: http://www.php.net/manual/en/mysqli.real-escape-string.php
Upvotes: 0
Reputation: 11393
You are using mysql_real_escape_string
instead of mysqli_real_escape_string
.
Fix that and it will work better!
Upvotes: 1
Reputation: 13558
check out the function mysqli_real_escape_string()
i should also note that the prefered method for escaping strings these days is parameter binding
Upvotes: 5