Avatar ·

How to properly sanitize user input in PHP from XSS and SQL injections?

Hello everyone! I'm a beginner PHP developer, writing my first website — a simple guestbook. Users leave a name and a message, which I save in MySQL and then display on the page.\n\nCurrently my code looks something like this:\n\n```php\n// Saving to DB\n$name = $_POST['name'];\n$message = $_POST['message'];\n$sql = "INSERT INTO comments (name, message) VALUES ('$name', '$message')";\nmysqli_query($conn, $sql);\n\n// Displaying on the page\necho "

$name: $message

";\n```\n\nI noticed that if you enter something like `` in the name field, a popup appears when displaying the message. And if you enter `' OR '1'='1`, the query seems to break.\n\nI've read that you need to "sanitize" input, but I don't understand how to do it correctly. There are tons of advice on the internet