0

My PHP form is designed to insert data to a MySQL database. It's working great, except when there is an apostrophe in my input. Then, I get this error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'fdfdf','fdfdf')' at line 2

This is my first project using PHP. Can someone please provide sample code for how to escape the apostrophe?

<html>
<body>
<form action="http://thefaithperspective.com/verses">
    <input type="submit" value="Add Another" />
</form>
</body>
</html>


<?php
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";

$verse= $_POST['verse'];
$book= $_POST['book'];
$reference = $_POST['reference'];


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO myverses (versetext, book, reference)
VALUES ('$verse','$book','$reference')";
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
Dakota Lynch
  • 169
  • 2
  • 11
  • **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or **any** user data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Feb 25 '18 at 23:58
  • Do try and get out of the habit of cluttering up your code with needless things like `=== true`. Many functions are designed to return values that evaluate as logically true or false so that's redundant. – tadman Feb 25 '18 at 23:58
  • I'm aware of injection vulnerabilities, but this form will be used only by me on a password-protected web page. – Dakota Lynch Feb 26 '18 at 00:04
  • That's the wrong attitude to have. You do not know if that protection might break in the future, if your firewall is misconfigured, or if someone else takes your code and deploys it in another application without your knowledge because it appears to work well. Do it right the first time, do not take shortcuts. You've already demonstrated the cost of cutting corners by having to ask this question, something that would never have been necessary if you used placeholder values in the first place. – tadman Feb 26 '18 at 00:06
  • Typical XY problem, once you fix the injection problem you fix the problem you think you need to fix. – Lawrence Cherone Feb 26 '18 at 00:15

0 Answers0