I am new to mysqli i wanted to check if email already exists in database with php and mysqli
Here is what i have done so far:
ini.php
<?php
session_start();
require 'connect.php';
include 'user.func.php';
?>
connect.php
<?php
$con = new mysqli('host', 'user', 'password', 'db');
if($con->connect_errno > 0){
die('Sorry, We\'re experiencing some connection problems.');
}
?>
register.php
<?php
include 'ini.php';
?>
<form action="" method="post">
<p>Username:<br/><input type="text" name="reg_name" maxlength="50" ></p>
<p>Email:<br/><input type="text" name="reg_email" size="35" maxlength="50" ></p>
<p>Password:<br/><input type="password" name="reg_password" maxlength="50" ></p>
<p>Re-type Password:<br/><input type="password" name="reg_re_password" maxlength="20"></p>
<p><input type="submit" value="Register" ></p>
</form>
<?php
include 'validate.php';
?>
validate.php
<?php
if(isset ( $_POST['reg_name'],$_POST['reg_email'], $_POST['reg_password'] )) {
$errors = array();
$name = $_POST['reg_name'];
$email = $_POST['reg_email'];
$password = $_POST['reg_password'];
$re_password = $_POST['reg_re_password'];
if(empty($name) || empty($email) || empty($password) || empty($re_password)){
$errors[] = 'All fields are required';
} else {
if(strlen($name) > 50 || strlen($email) > 50 || strlen($password) > 50) {
$errors[] = 'One or more field has too long Characters';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE && $password !== $re_password){
$errors[] = 'Enter valid email address and password do not match';
}else{
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
$errors[] = 'Please enter a valid email address';
}
if($password !== $re_password){
$errors[] = 'Both passwords do not match';
}
if(user_exists($email) > 0){
$errors[] = 'That email is already been registered';
}
}
}
if (!empty($errors)) {
foreach ($errors as $errors) {
echo '<strong>',$errors,'</srtong><br />';
}
}else{
echo 'Registered';
}
}
?> user.func.php
<?php
function user_exists($email) {
$con = new mysqli('host', 'user', 'password', 'db');
$query = "SELECT * FROM users WHERE email = ?";
$stmt = $con->prepare($query);
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
return $stmt->num_rows;
}
return false;
}
?>
This code shows all the other errors but doesn't check if the email exist. Instead it shows registered even when i enter email that is already in database.
I have database named 'test'. And table 'users' with columns user_id, username, email and password.
Can anyone tell how to code mysqli query for this?
I used this code in mysql
function user_exists($email) {
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT COUNT('user_id') FROM 'users' WHERE 'email'='$email'");
return (mysql_result($query, 0) == 1) ? true :false;
}