1

I have a heredoc variable like this:

$status=<<<EOT
<p>hello world</p>
<p>I'm <strong>really</strong>OK!</p>
<p></p>
EOT;

And I want to insert it into my MySQL DB with whitespaces by PHP like this:

query="INSERT INTO requests (ID,title) VALUES ('$ID','$status')";

But I can't do that. What should I do to be allowed to insert that?

3
  • SQL escaping? Got any error messages? How exactly does the result differ? Is it about linebreaks not displaying in HTML context? Commented Apr 19, 2016 at 13:45
  • Possible duplicate of how to insert HTML code into DB using php Commented Apr 19, 2016 at 13:55
  • You have an apostrophe in your text which is confusing the database. Use a prepared statement instead. Commented Apr 20, 2016 at 19:26

2 Answers 2

1

You can do it in 2 ways:

Using mysqli_real_escape_string() like this:

$mydb = new mysqli("localhost","root","FedAnd11");

$status=<<<EOT
<p>hello world</p>
<p>I'm <strong>really</strong>OK!</p>
<p></p>
EOT;

$query="INSERT INTO requests (ID,title) VALUES ('$ID','".$mydb->real_escape_string($status)."')";

or if you don't have a db connection yet,

$status=<<<EOT
<p>hello world</p>
<p>I'm <strong>really</strong>OK!</p>
<p></p>
EOT;

$status = str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $status);

$query="INSERT INTO requests (ID,title) VALUES ('$ID','$status')";

If I've understood you problem.

Another thing you can do, is to use a mysql prepared statement, if you really want to put $status as is, like this:

$status=<<<EOT
<p>hello world</p>
<p>I'm <strong>really</strong>OK!</p>
<p></p>
EOT;

$stmt = $dbConnection->prepare('INSERT INTO requests (ID,title) VALUES (?,?)');
$stmt->bind_param('is', $ID,$status);

$stmt->execute();

I supposed the $ID is integer.

Sign up to request clarification or add additional context in comments.

1 Comment

I'd suggest moving the prepared statement to the top; when answering a question it's always a good idea to push them to the best method. Note that you don't know what database API they're using, could be PDO or the ancient mysql API.
0

Try using addslashes()

$status = addslashes($status);
query="INSERT INTO requests (ID,title) VALUES ('$ID','$status')";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.