0

So escaping a normal String is no problem with

$username = $mysqli->real_escape_string("Peter");

But how do I escape a global variable with user input? For example, I get the Username from the input field and saved it in $username. What have I to do now?

$username = ($_POST["Username"]);`
Dharman
  • 30,962
  • 25
  • 85
  • 135
CoreIce
  • 15
  • 5
  • 1
    It depends on what you're planning on doing with the value. Escaping isn't for protection when you _receive_ a value. It's for protection when you _use_ the value. Different uses needs different escaping. If you're going to use it in a database query, you shouldn't escape it at all and use prepared statements with placeholders. – M. Eriksson Jan 11 '20 at 15:52
  • I want to prevent an SQL injection in my user input field and then save it inside my MYSQL database – CoreIce Jan 11 '20 at 15:56
  • Simply: `$username = $mysqli->real_escape_string($_POST["Username"]);`. However, I'd use a prepared statement instead. It's a lot better/safer. – Funk Forty Niner Jan 11 '20 at 15:56
  • 2
    Then you should read up on prepared statements instead of manually escape the data. – M. Eriksson Jan 11 '20 at 15:56
  • @FunkFortyNiner I already tried that but get the error "Fatal error: Uncaught Error: Call to a member function real_escape_string() on null in /var/www/html/RegTest.php:28 Stack trace: #0 {main} thrown in /var/www/html/RegTest.php on line 28" – CoreIce Jan 11 '20 at 15:57
  • 1
    you would not want to use `real_escape_string` in conjunction with a prepared statement anyway – Professor Abronsius Jan 11 '20 at 15:59

0 Answers0