0

I have made some adjustments to my code and now is working , i just wonder if this is a good and safe way or i have to change or add something to the code.

<?php 
session_start();
$db = mysqli_connect("localhost", "root", "", "store");
if (isset($_POST['register_btn']))  {
    $username= mysqli_real_escape_string($db, $_POST['username']);
    $email = mysqli_real_escape_string($db, $_POST['email']);
    $pas= mysqli_real_escape_string($db, $_POST['pas']);
    $stmt = $db->prepare("INSERT INTO users (username,email,pas) 
                          VALUES(?,?,?)");
    $stmt->bind_param("sss", $username, $email, $pas);
    $stmt->execute();       
    mysqli_query($db, $stmt);
    header("location: login.php");
}
?>
Dave
  • 3,073
  • 7
  • 20
  • 33
OneBeginner
  • 139
  • 2
  • 9
  • 1
    Don't use both `mysqli_real_escape_string()` AND prepared statements. Just use prepared statements alone ;-) And you don't need `mysqli_query($db, $stmt);`, you already executed the query. – Qirel Oct 01 '16 at 13:02
  • Prepared statement best option but y r u using mysqli_query() – devpro Oct 01 '16 at 13:02
  • 1
    http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – Jeff Oct 01 '16 at 13:04
  • @Qirel Im not rly sure how to do this without mysqli_real_escape_string() – OneBeginner Oct 01 '16 at 13:08
  • @OneBeginer Instead of `$pas= mysqli_real_escape_string($db, $_POST['pas']);`, it should simply be `$pas = $_POST['pas'];` (same for the other two) - and remove `mysqli_query($db, $stmt);` altogether. – Qirel Oct 01 '16 at 13:12
  • @Qirel I made the changes and it works , thank you very much for your help . And now this should be secure against injections ? and should i use prepare statments for login and any others inputs into the DataBase aswell? – OneBeginner Oct 01 '16 at 13:24
  • You should *always* use prepared statements. You *can* use `mysqli_query()` when you are dealing with static queries (not variables in the query), but if you already use prepared statements - you've laid the groundwork should you need to edit that query later on. And yes, this will protect you from SQL injections. – Qirel Oct 01 '16 at 13:26
  • @Qirel Ok , thank you very much for all the help , i have been struggled with this. – OneBeginner Oct 01 '16 at 13:31

0 Answers0