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?

Jose Rojas
  • 3,490
  • 3
  • 26
  • 40
user3416269
  • 375
  • 1
  • 5
  • 10
  • SQL escaping? Got any error messages? How exactly does the result differ? Is it about linebreaks not displaying in HTML context? – mario Apr 19 '16 at 13:45
  • Possible duplicate of [how to insert HTML code into DB using php](http://stackoverflow.com/questions/24631088/how-to-insert-html-code-into-db-using-php) – geeksal Apr 19 '16 at 13:55
  • You have an apostrophe in your text which is confusing the database. Use a prepared statement instead. – miken32 Apr 20 '16 at 19:26

2 Answers2

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.

lamp76
  • 333
  • 1
  • 10
  • 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. – miken32 Apr 20 '16 at 19:27
0

Try using addslashes()

$status = addslashes($status);
query="INSERT INTO requests (ID,title) VALUES ('$ID','$status')";
Amit Visodiya
  • 856
  • 6
  • 18