skip to Main Content

I am making a WordPress plugin. I have to create a Name and email checker.
I have a form with POST method. In this form you fill your email and name

<form method="post">
    <input type="text" name="yourname" placeholder="name" required>
    <input type="text" name="mail" placeholder="email" required>
    <input class="btnAdd" type="submit" value="Add">
</form>

Then i want to make a sql query to check if there is a user with the email that has been filled in.
I did console.log $EmailCheckResults` from below here. and it gives this back:

SELECT user_email FROM users WHERE user_email = 0

Code:

global $wpdb;
        
$emailToCheck = $_POST['mail'];     
$EmailCheckResults = $wpdb->prepare("SELECT user_email FROM users WHERE user_email = %d", $emailToCheck);
$CheckResults = $wpdb->get_var($EmailCheckResults);

any ideas why %d is 0? even if i fill in the email input?

3

Answers


  1. According documentation %d mean – digit placeholder. Use %s for strings.

    Login or Signup to reply.
  2. An email-id is always a string, so use %s instead of %d

    %s represents a string.

    %d represents digits.

    So the code needs to be:

    $EmailCheckResults = $wpdb->prepare("SELECT user_email FROM users WHERE user_email = %s", $emailToCheck);
    
    Login or Signup to reply.
  3. In WordPress, there is a function called email_exists( $email ) which you can use for checking if the email is already used by another user or not.
    If the email is already used, then the existing user_id is returned.

    Check this function: https://developer.wordpress.org/reference/functions/email_exists/

    Hope this will also help.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search