-3

i am using a form (contains only email) that sends data with ajax to my php file where i need to check if the email that the user entered exists in my database table.

The table contains these columns: id, name, email, timestamp.

In variable $email i have stored the email that the user has added in the form.

i am using PDO to connect to my database with this code

    try {
    $db = new PDO('mysql:unix_socket=/tmp/mysql51.sock;host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
    } catch (PDOException $e) {
        echo 'Pripojenie zlyhalo: ' . $e->getMessage();
    }

    $query_user = $db->prepare("SELECT COUNT FROM koniecinvite as pocet WHERE email='$email'");
    $query_user->execute();
    $pocet = $query_user->fetchObject();

    if($pocet>0){
        http_response_code(200);
        echo "Email exists";
    }else {
        http_response_code(200);
        echo "Email does not exists";
    }

It is not working. I know i need to get the count of the rows with the email, but i need some help here.

Can somebody help me with this?

EDIT: From error reporting i get "Notice: Object of class stdClass could not be converted to int in "

MichalCh
  • 201
  • 3
  • 15

1 Answers1

1

First of all:

SELECT COUNT FROM koniecinvite as pocet WHERE email='$email'"

Should be:

SELECT COUNT(*) FROM koniecinvite as pocet WHERE email='$email'"

Also $email must be escaped because of the danger of SQL Injection: https://en.wikipedia.org/wiki/SQL_injection

So the code snippet that does the query should be (please keep in note that on string I DO NOT USE THE VARIABLE, but instead a :something that will be raplaced by variable with bindParam):

$query_user = $db->prepare("SELECT COUNT FROM koniecinvite as pocet WHERE email=:email");
$query_user->bindParam(":email","$email")
$query_user->execute();
Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164