Register

How to check if email exists in the database?

Alas, it’s entirely wrong. The result of the query has nothing to do with the number of rows found. An empty result is still a legitimate result, it cannot be false only because the query didn’t find anything.

In fact, the code to check whether some value exists in the database would be the just a regular routine for select queries.

And of course, a prepared statement is obligatory. NEver ever put a data variable directly tho the query. Always use a placeholder instead!

How to check whether a value exists?

To check whether a particular value exists in the database, you simply have to run just a regular SELECT query, fetch a row and see whether anything has been fetched.

Given $pdo contains a valid PDO instance, the code would be

$email = "test@example.com";
$stmt = $pdo->prepare("SELECT * FROM users WHERE email=?");
$stmt->execute([$email]);
$user = $stmt->fetch();
if (
$user) // email found
> else // or not
>

Here we are selecting a row matching our criteria, then fetching it and then checking whether anything has been selected or not.

Notes

It also makes sense to select just a single constant value to reduce overhead a little, if we aren’t going to use any selected data. For that purpose simple replace * with 1 . Having a function or a class’ method for the purpose also would be handy:

 function emailExists($pdo, $email) $stmt = $pdo->prepare("SELECT 1 FROM users WHERE email=?"); 
$stmt->execute([$email]);
return
$stmt->fetchColumn();
)

if (
emailExists($pdo, $email)) // found
>

here we are using a handy PDO’s method fetchColumn that returns a selected value or false otherwise. Given 1 will be treated as true by if statement, we can return this method’s result directly. However, in case you prefer strict typing, the return value could be cast to boolean:

 return (bool)$stmt->fetchColumn(); 

Also, as can be seen from above, a popular solution with getting the number of rows returned is just unnecessary. Calling $stmt->numRows() is just superfluous, not to mention it can be just unavailable due to some drivers or settings.

  • SELECT query with PDO
  • INSERT query using PDO
  • UPDATE query using PDO
  • How to connect to MySQL using PDO
  • PDO Examples
  • Authenticating a user using PDO and password_verify()
  • Select the number of rows using PDO
  • How to create a WHERE clause for PDO dynamically
  • How to create a prepared statement for UPDATE query
  • DELETE query using PDO
  • Getting a nested array when multiple rows are linked to a single entry
  • How to execute 1000s INSERT/UPDATE queries with PDO?
  • Adding a field name in the ORDER BY clause based on the user’s choice
  • INSERT helper function for PDO Mysql
  • PDO Examples
  • PDO Examples
Читайте также:  Java iso time format

Got a question?

I am the only person to hold a gold badge in , and on Stack Overflow and I am eager to show the right way for PHP developers.

Besides, your questions let me make my articles even better, so you are more than welcome to ask any question you have.

SEE ALSO:

  • Top 10 PHP delusions
  • PDO Examples
  • Mysqli Examples
  • Principles of web-programming
  • SELECT query with PDO
  • INSERT query using PDO
  • UPDATE query using PDO
  • How to connect to MySQL using PDO
  • PDO Examples
  • Authenticating a user using PDO and password_verify()
  • Select the number of rows using PDO
  • How to create a WHERE clause for PDO dynamically
  • How to create a prepared statement for UPDATE query
  • DELETE query using PDO
  • Getting a nested array when multiple rows are linked to a single entry
  • How to execute 1000s INSERT/UPDATE queries with PDO?
  • Adding a field name in the ORDER BY clause based on the user’s choice
  • INSERT helper function for PDO Mysql
  • PDO Examples
  • PDO Examples

Latest comments:

  • 17.07.23 21:18
    Jim for (The only proper) PDO tutorial:
    Thanks for the reply! I was hoping you would know if what I’m attempting is even possible! :).
    read more
  • 16.07.23 00:35
    Jim for (The only proper) PDO tutorial:
    Hi, I just discovered this site today, so first and foremost, thank you for all your work.
    read more
  • 27.06.23 05:30
    Jeff Weingardt for MVC in simpler terms or the structure of a modern web-application:
    I was just curious what you find the most effective way to learn php and become proficient? so.
    read more
  • 23.06.23 00:57
    Michael for INSERT query using PDO:
    I read your bit on not needing to check the status of execution. I’m curious, if I needed to.
    read more
  • 10.06.23 17:18
    Ian McKinnon for How to create a search filter for mysqli:
    Please tell me how I can convert this into a prepared statement. ‘A’ indicates that the retrieved.
    read more

Add a comment

Please refrain from sending spam or advertising of any sort.
Messages with hyperlinks will be pending for moderator’s review.

Comments:

Thank you so much. I would like to know how to check multiple values, if telephone and email exists in the database. Thanks in advance

How to check if a time has been taken by other user? I don’t know if I’m doing it correctly, but what I’m trying to do is to check if the time entered by the user is already taken by someone. Sample if on the DB as already start_time from 08:30:00AM and end_time is 10:00:00 the other user will not be able to add another time between this (time from 08:30:00AM to end_time is 10:00:00) will be have to choose another time like 07:00am to 08:29am or 10:01am to 12:00pm. I found some samples but I got no success. This is what I got so far

$query = "SELECT start_time, end_time FROM horarios WHERE user='$subcat' 
AND start_time >= '
$start_time' AND end_time $end_time';";

$result= pg_query($con, $query);
$rows = pg_num_rows($result);
$query = @pg_query ($con, $sql);
if (
$query == NULL) echo "the number $subcat is busy";
exit (
0);
>else (
$rows===0) $sql = "insert into. ;";
echo
$sql;
>

Wow, nice job on all the documentation. Approaching age 70, I’ve been fooling with PHP since it was first available. Your PDO information is really helpful as I attempt to amuse or frustrate myself by migrating a basic personal project into PDO.

Reply:

Hello Doug! I wish you best of luck with your enterprise! Do not hesitate to ask any questions, your questions let me make the site better

Reply:

I would usually write «SELECT COUNT() FROM users WHERE email=?» to check if a value exist. Is there any reason to use 1 instead of COUNT() ?

Your site is incredible. I think it’s the best explained on the web. I hope it stays online for along time. I’m new to PHP and you’ve helped me a lot. I would ask if you could do an example on PHPmailer. I need to get the registration form error array over to the PHPmailer code and don’t send an email if the form has errors. You really are very good at PHP. Thanks for your great service.

Источник

email_exists() │ WP 2.1.0

Если email существует, то выведем ID пользователя, зарегистрированного с этим email. В противном случае, выведем надпись, что введенное мыло свободно и пользователь может быть зарегистрирован.

$email = ‘myemail@example.com’; if( email_exists( $email ) ) < echo "Этот e-mail зарегистрирован на пользователя с ID: " . email_exists($email); >else

Список изменений

Код email_exists() email exists WP 6.2.2

function email_exists( $email ) < $user = get_user_by( 'email', $email ); if ( $user ) < $user_id = $user->ID; > else < $user_id = false; >/** * Filters whether the given email exists. * * @since 5.6.0 * * @param int|false $user_id The user ID associated with the email, * or false if the email does not exist. * @param string $email The email to check for existence. */ return apply_filters( 'email_exists', $user_id, $email ); >

Cвязанные функции

Условные теги (все)

  • cat_is_ancestor_of()
  • category_exists()
  • comments_open()
  • has_block()
  • has_category()
  • has_custom_header()
  • has_excerpt()
  • has_nav_menu()
  • has_post_thumbnail()
  • has_shortcode()
  • has_tag()
  • has_term()
  • have_comments()
  • have_posts()
  • in_category()
  • in_the_loop()
  • is_404()
  • is_active_sidebar()
  • is_admin()
  • is_admin_bar_showing()
  • is_archive()
  • is_attachment()
  • is_author()
  • is_blog_admin()
  • is_category()
  • is_child_theme()
  • is_comment_feed()
  • is_customize_preview()
  • is_date()
  • is_day()
  • is_dynamic_sidebar()
  • is_email()
  • is_embed()
  • is_feed()
  • is_front_page()
  • is_header_video_active()
  • is_home()
  • is_local_attachment()
  • is_login()
  • is_main_query()
  • is_month()
  • is_multi_author()
  • is_multisite()
  • is_nav_menu()
  • is_network_admin()
  • is_new_day()
  • is_page()
  • is_page_template()
  • is_paged()
  • is_plugin_active()
  • is_post_type_archive()
  • is_post_type_hierarchical()
  • is_preview()
  • is_robots()
  • is_search()
  • is_single()
  • is_singular()
  • is_ssl()
  • is_sticky()
  • is_tag()
  • is_tax()
  • is_taxonomy_hierarchical()
  • is_textdomain_loaded()
  • is_time()
  • is_trackback()
  • is_user_admin()
  • is_user_logged_in()
  • is_year()
  • pings_open()
  • post_exists()
  • post_password_required()
  • shortcode_exists()
  • tag_exists()
  • taxonomy_exists()
  • term_exists()
  • term_is_ancestor_of()
  • wp_attachment_is()
  • wp_doing_ajax()
  • wp_doing_cron()
  • wp_is_mobile()
  • wp_is_post_autosave()
  • wp_is_post_revision()
  • wp_is_using_https()
  • wp_script_is()

Остальное

  • auth_redirect()
  • count_many_users_posts()
  • count_user_posts()
  • count_users()
  • get_author_posts_url()
  • get_current_user_id()
  • get_edit_user_link()
  • get_editable_roles()
  • get_the_author()
  • get_the_author_link()
  • get_the_author_posts_link()
  • get_the_modified_author()
  • get_user_by()
  • get_userdata()
  • get_users()
  • sanitize_user()
  • the_author_link()
  • the_author_posts()
  • the_author_posts_link()
  • the_modified_author()
  • username_exists()
  • validate_username()
  • wp_dropdown_roles()
  • wp_dropdown_users()
  • wp_get_current_user()
  • wp_list_authors()
  • wp_list_users()
  • wp_set_current_user()

Тимур, подскажите пожалуйста, можно ли как то проверить, при отправки комментария с сайта wp, адрес почты комментатора на существование вообще. Бывает просто люди пишут комментарий, а почту указывают левую. Или плагин типа DM Confirm Email, чтобы отправлял ссылку для подтверждения почты на эту же почту комментатора.

Невозможно проверить, существует или нет почтовый ящик, без участия владельца ящика (т.е. без подтверждения через письмо). Если хочешь, чтобы только с существующими емейлами люди оставляли комментарии, то делай регистрацию на сайте и возможность комментирования только для зарегистрированных пользователей.

Источник

how to check email already exist in database in php? – 5 Ways To Check if Email already exists Using PHP

how to check email already exist in database in php: every user get the simple solution for the how to check if an email address already exists in the database in php?

how to check email already exist in database in php

Validate the email if already exists. The validation of email exist is a restriction to the user for duplicate remove or deleted.

5 Ways To Check if Email already exists Using PHP

Set Email Column as UNIQUE on the Database

Validate Email using MySQL SELECT query with WHERE clause

Example – how to check data already exist in database in php

check username and email already exists

 0) < $row = mysqli_fetch_assoc($res); if($email==isset($row['email'])) < echo "email already exists"; >if($membername==isset($row['membername'])) < echo "Sorry, membername already exists"; >> else < //do your insert code here or do something (run your code) >?>

Check if username is already taken with PHP and MySQL

Create two files in your favorite text editor:

    
Register
">
">
/body>

styles.css
Now the styles.css file:

#signup_frm h1 < text-align: center; >body < background: #A9D9C3; >#signup_frm < width: 37%; margin: 100px auto; padding-bottom: 30px; border: 1px solid #918274; border-radius: 5px; background: white; >#signup_frm input < width: 80%; height: 35px; margin: 5px 10%; font-size: 1.1em; padding: 4px; font-size: .9em; >.userfrm_err span < width: 80%; height: 35px; margin: 3px 10%; font-size: 1.1em; color: #D83D5A; >.userfrm_err input < border: 1px solid #D83D5A; >#reg_btn

 0) < $name_error = "Sorry. membername already taken"; >else if(mysqli_num_rows($res_e) > 0)< $email_error = "Sorry. email already taken"; >else < $query = "INSERT INTO members (membername, email, password) VALUES ('$membername', '$email', '".md5($password)."')"; $results = mysqli_query($db, $query); echo 'Saved!'; exit(); >> ?>

I hope you get an idea about how to check email already exist in database in php.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Источник

Оцените статью