Link to home
Start Free TrialLog in
Avatar of Mandy Blyss
Mandy BlyssFlag for Australia

asked on

Problem inserting value with a single quote in MySQL query.

Problem with my query, when adding a value that has a single quote to a database field.

eg. //-- values
        $value1 = "Peter";
        $value2 = "O'Leary";
        $value3 = "Contact Person";
     //-- query
        $stmt = $mysqli->prepare("INSERT INTO table1 (field1, field2, field3) VALUES (?,?,?)");
        $stmt->bind_param('sss',  $value1, $value2, $value3);
        $stmt->execute();
        $newId = $mysqli->insert_id;
        $stmt->close();

This does not insert anything, and $newId has no value.

So it seems I have a really silly question... I'm sure it's something really obvious, but I'm dead tired and can't figure it out.

I've tried...
$value2 = htmlspecialchars("O'Leary", ENT_QUOTES, 'UTF-8');
$value2 = mysqli_real_escape_string($mysqli, "O'Leary");
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Have you tried doubling the quotes (2 single quotes)?
        $value2 = "O''Leary";

Open in new window

Avatar of Daniel Pineault
Daniel Pineault

mysqli_real_escape_string() should do the trick here?!

What about trying addslashes()?
$value2 = addslashes("O'Leary");

Open in new window


As for the $newId, shouldn't you be using lastInsertId()?
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mandy Blyss

ASKER

Hi Eric, Daniel & Julian,

Thank you all for the great information. In this case, Julian is bang-on. My query was perfectly fine (that's why I was going in loops). However the problem was in fact in the Database. The content I was trying to enter in to the DB field was over the max permitted, so it was having an issue.

In past, I always thought the data would be simply "cut off", but perhaps with the new PHP 7.x and MySQL 5.7.x there are tighter controls on passing the data... ??

Again, thank you to all.

Julian (you're a star!), I will remember to use that code again in future, to get any errors from the DB.
You are welcome.
Thanks for the assistance and information offered - it assisted to ensure I found the issue.