0

I have a problem. I need to pass a string to the MySQL database which has a \n in it and I want to save it in the database but it is removing \n and replacing it with line break.

PHP code to insert data to the database:

$sql = "INSERT INTO pusher_api_holder_v2 (name, text) VALUES ('$site_name', '$text')";
Ar Rakin
  • 534
  • 3
  • 15
  • ou are open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized prepared statements instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) and [MySQLi](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even data from the database, [you are still at risk of corrupting your data](https://bobby-tables.com/). If this is a school project. Best time to learn. How to do things right. – Jason K Mar 28 '23 at 19:18
  • 5
    Use prepared statements. The double quotes around the larger sql string is turning `\n` into line breaks. Prepared statements are for more than just SQL injection, it also makes sure your text is inserted the way you want without having to worry about quotes! – aynber Mar 28 '23 at 19:20
  • Does this answer your question? [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – user3783243 Mar 28 '23 at 19:48
  • Does this answer your question? [How to include a PHP variable inside a MySQL statement](https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement). Frankly it's terrifying how many questions we get here every day where people haven't been taught this kind of basic stuff. – ADyson Mar 28 '23 at 23:10

1 Answers1

2

I think you should use pdo or mysqli to get rid of for all kind of injections and your text will be inserted as you want it.

You can try this

$insert = $db->prepare(”INSERT INTO pusher_api_holder_v2 (name, text) VALUES (?, ?)”);
$insert->execute(array($username,$text));
If($insert->rowCount() >0){echo ”successfully inserted to db”;}else{echo “fail”;}
Atilla
  • 25
  • 5