1

I'm trying to prevent sql injection by binding parameters but when I convert my code to binded parameters, the mysqli_num_rows no longer works.

I have a simple email authentication that I want to check against the database for duplicate rows:

Below my code :

    $checkDup = "SELECT Email FROM users WHERE Email='{$_POST['Email']}'";
    $resultDup = mysqli_query($db,$checkDup);

    //If not 0 duplicates (another one exists) create an error alert
    if(!mysqli_num_rows($resultDup) == 0){
        echo '<script language="javascript">
                alert("Email Already Exists");
                window.location.href = "Sign Up.php";
            </script>';
        unset($_POST);
    }

After binding it -

Its Not right type error i got :

$checkDup = $db->prepare("SELECT Email FROM users WHERE Email= ?");
$checkDup->bind_param("s", $_POST['Email']);


//If not 0 duplicates (another one exists) create an error alert
if(!mysqli_num_rows($checkDup->execute()) == 0){
    echo '<script language="javascript">
            alert("Email Already Exists");
            window.location.href = "Sign Up.php";
        </script>';
    unset($_POST);
}
Manthan Dave
  • 2,137
  • 2
  • 17
  • 31
Curious Cat
  • 309
  • 1
  • 3
  • 14
  • 1
    By the way you should use `mysqli_num_rows($checkDup->execute()) > 0` instead of `!mysqli_num_rows($resultDup) == 0` – rbr94 Dec 08 '16 at 08:51

1 Answers1

0

You need to use num_rows()

$checkDup = $db->prepare("SELECT Email FROM users WHERE Email= ?");
$checkDup->bind_param("s", $_POST['Email']);
$checkDup->execute();
$checkDup->store_result();


if ($checkDup->num_rows  > 0) {

echo '<script language="javascript">
            alert("Email Already Exists");
            window.location.href = "Sign Up.php";
        </script>';
    unset($_POST);
}

refer : http://php.net/manual/en/mysqli-stmt.num-rows.php

Kalidass
  • 424
  • 3
  • 18
  • I think this is MySQLi because when I try your code I get "Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetchColum" – Curious Cat Dec 08 '16 at 09:00
  • $checkDup = $db->prepare("SELECT Email FROM users WHERE Email= ?"); $checkDup->bind_param("s", $_POST['Email']); $checkDup->execute(); $checkDup->store_result(); if ($checkDup->num_rows > 0) { echo ''; unset($_POST); } – Kalidass Dec 08 '16 at 09:03
  • Thanks a lot. I wasn't aware you needed to store the result. This seemed to have fixed it. – Curious Cat Dec 08 '16 at 09:10
  • you are welcome .... – Kalidass Dec 08 '16 at 09:12