Home > Mobile >  PHP Signup not working using prepare sql statement
PHP Signup not working using prepare sql statement

Time:11-05

I wrote code for sign up using php and mysql prepare statement. I dont know why its not inserting record! Can anyone tell where is the problem Its not displaying any error or success message even here is my adduser.php code

<?php 

 include 'config.php';

 //checkusername
 $check = $con->prepare("select username from users");

 while($row = $check->fetch(PDO::FETCH_ASSOC)){
     if($row['username'] == $_POST['username'])
        echo -1;
     else{

        $sql = $con->prepare("insert into users(name,username,password) values(?,?,?)");
        $sql->bindParam($name,$username,$password);
        $name = $_POST['name'];
        $username = $_POST['username'];
        $password = md5($_POST['password']);
        $sql->execute();
            echo 1;
     }
   }

 ?>

CodePudding user response:

$sql->bindParam($name,$username,$password);

is incorrect. You must bind each parameter via a separate call to bindParam.

See the argument list and examples in the PHP manual page for bindParam to understand what the function accepts as input, and how to use it in practice.

e.g.

$sql = $con->prepare("insert into users(name,username,password) values(?,?,?)");
$sql->bindParam(1, $name);
$sql->bindParam(2, $username);
$sql->bindParam(3, $password);
...
$sql->execute();

Alternatively, you can simply call the execute function and pass in an array of parameters that way:

$sql = $con->prepare("insert into users(name,username,password) values(?,?,?)");
$params = [$name, $username, $password];
$sql->execute($params);

P.S. if you were not getting any kind of error or indication of this problem when you ran the code, then please ensure you enabled PHP's error logging feature and PDO's exception reporting mode so you can get detailed information about any errors in your code.

P.P.S. Please don't store passwords using the obsolete, insecure md5 algorithm - that is a security risk. Learn about PHP's built-in, up-to-date, secure password hashing and verification functions instead.

P.P.P.S. It makes no sense to query all the users and loop through them to find any existing records with the same username. This is very inefficient. You can filter the results much more quickly and efficiently using a SQL WHERE clause in the SELECT, e.g. select username from users where username = ?. Bind the username to that, and you'll get a single row back in response if there's a match.

  • Related