This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I want to prevent user from registering an email address that is already set in my table. I am doing it like this:
$emailcheck = $bdd->prepare('SELECT COUNT(*) FROM ' . DB_TABLE . ' WHERE MATCH(email) AGAINST '.$_POST['email'].' ');
$emailcheck->execute();
$emailcheckrows = $emailcheck->fetch();
if ($emailcheckrows > 0) {
$_SESSION['err_msg']="This email address is already registered";
$error=true;
$emailcheck->closeCursor();
}
But this doesn't work. I have already tried almost everything (also with LIKE, = and in-array). The "if" is not executed when I enter an already submitted email.
Any idea ? Thank you
you can use it as an simple function like:
class Validation {
public static function emailUnique($conn, $email)
{
$sql = "SELECT email FROM formular WHERE email = '".$email."'";
$emailUnique = $conn->query($sql);
return (boolean) $emailUnique->num_rows;
}
}
this returns a true if an entry has been found and false if not and then you can call your function in your script like this. i've used this together with bootstrap-alerts:
$errorField = "";
$labelClass = array(
"emailUnique"=>"",
);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$errorMessages["emailUnique"] = Validation::emailUnique($conn ,$email);
$DisplayErrorForm = array();
$hasErrors = false;
$formErrorMessage = "";
foreach ($labelClass as $key=>$value) {
if($errorMessages[$key]){
$labelClass[$key] = "has-error";
$hasErrors = true;
$DisplayErrorForm["emailUnique"] = array("style" => "red", "text" => "Email is already taken");
if($key == "emailUnique"){
$formErrorMessage .= "<li style='" . $DisplayErrorForm["emailUnique"]["style"] . "'>" . $DisplayErrorForm["emailUnique"]["text"] . "</li>";
}
}
}
if(count($DisplayErrorForm)) {
$errorField = "<div class=\"alert alert-danger\">".
"<strong>Whoops!</strong> There were some problems with your input.<br><br>".
"<ul>".$formErrorMessage."</ul>".
"</div>";
}
if (!$hasErrors) {
//Do the database input
and then down in your html part call the $errorField
<div>
<?php echo $errorField; ?>
</div>
The answer was to bind the value and use rowCount(). It worked with the following code:
$emailcheck = $bdd->prepare('SELECT * FROM ' . DB_TABLE . ' WHERE email = ?');
$emailcheck->bindValue( 1, $_POST['email'] );
$emailcheck->execute();
if ($emailcheck->rowCount() > 0) {
$_SESSION['err_msg']="e-mail addresse already registered";
$erreur=true;
$emailcheck->closeCursor();
header ('Location: form.php');
}
query instead of prepare is maybe easier..
Related
This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 7 years ago.
I'm making a PHP Newsletter script, I'm not very experienced in code, but I try my best to improve, I just need a few ideas in order to make this work.
function validate(){
if(isset($_POST['email'])){
$email = $_POST["email"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<br>Va rugam introduceti o adresa valida de email";
}else{
return 1;
}
}
}
function checkmail(){
if(validate()==1){
if(isset($_POST['email'])){
$email = $_POST['email'];
$sql = "SELECT * FROM subscribe WHERE email LIKE '$email'";
$connect = new mysqli("localhost", "root", "", "alexandru");
$result = mysqli_query($connect,$sql);
echo print_r($result);
}
}
}
I don't know how I can check the result of the query, I need some ideas, thanks
I have made this simple function which you can use.
function field_exists($field_name, $field_value, $table)
{
global $conn;
try
{
$s = $conn->prepare("SELECT * from $table where $field_name = :f_value");
$s->bindParam(':f_value', $field_value);
$s->execute();
if($s->rowCount() > 0)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Using this function, you can check any table for any value of the specified column.
So in your case, the $field_name would be email, $field_value would be $email and table would be subscribers.
Usage
if(field_exists("email", $email, "subscribers"))
{
//email exists
}
else
{
//email doesn't exist
}
The function would return true if this email in the table exists, and false if the email doesn't.
This code i use whithout oops concept in my practicle ithink it'll help
extract($_POST);
$qwe = "SELECT * FROM user_info where email= '$email'";
$result = mysqli_query($con, $qwe);
if (mysqli_fetch_row($result) >= 1) {
header("Location: userreg.php?err=msg");
}
else {
// query for what u want after check mail doesn't exist
}
This question already has an answer here:
PHP MySql - Check if value exists
(1 answer)
Closed 8 years ago.
I've got a database table with two columns:
EMAIL_ADDRESS and ACTIVATION_CODE
I need to make the script check if the Activation Code the user has submitted in the URL, matches the Email Address in the table. So far this isn't working.
$email = mysql_real_escape_string($_GET['email']);
$acticode = mysql_real_escape_string($_GET['code']);
$result = mysql_query("SELECT * FROM xActivate WHERE EMAIL_ADDRESS='$email',1");
if ($result = '$acticode') {
echo 'Code is valid';
} else {
echo 'Code is NOT valid';
}
check row with mysql_num_row
if(mysql_num_rows($result)>0){...}
and check valid code with
if(mysql_error())
You need to know the column in the database where the code is stored, also, you need to actually get the data
$email = mysql_real_escape_string($_GET['email']);
$acticode = mysql_real_escape_string($_GET['code']);
$code_found = false;
$result = mysql_query("SELECT * FROM xActivate WHERE EMAIL_ADDRESS='$email',1");
if($result) {
$row = mysql_fetch_assoc($result);
if($row) {
if ($row['codefield'] == $acticode) {
$code_found = true;
}
}
}
if($code_found) {
echo 'Code is valid';
} else {
echo 'Code is NOT valid';
}
I'm pretty new to both PHP and MySQL and I'm struggling to get my login system to function properly. The registration works fine, but when I run the login it doesn't recognise there is anything within the table matching the entered data. Below is the code I believe to be the problem area.
Thanks in advance.
<?php
function load($page = 'login.php')
{
$url = 'http://'.$_SERVER['HTTP_HOST'].
dirname($_SERVER['PHP_SELF']);
$url = rtrim($url,'/\/');
$url.= '/'.$page;
header("location:$url");
exit();
}
function validate($dbc,$email ='',$pwd='')
{
$errors = array();
if (empty($email))
{ $errors[] = 'Enter your email address.'; }
else
{ $e = mysqli_real_escape_string($dbc,trim($email));}
if (empty($pwd))
{ $errors[] = 'Enter your password.';}
else
{ $p = mysqli_real_escape_string($dbc, trim($pwd)); }
if (empty($errors))
{
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1)
{ $row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array( true, $row);}
else
{$errors[]='Email address and password not found.';}
}
return array(false,$errors);
}
I believe that you'll get what you're looking for if you change
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
to
$p = SHA1($p);
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = '$p'";
Whenever a PHP-to-MySQL query isn't performing as expected, my first step is to get a look at the SQL I'm actually passing to the database. In this case, it would be by inserting a line like echo '<p>$q</p>'; immediately after assigning the value of $q.
Sometimes it immediately becomes obvious that I've got a malformed query just by looking at it. If it doesn't, I copy the SQL code that appears and run it as a query within the database manager, to see what errors it throws and/or examine the resulting data.
Okay so I'm looping through the results that contains two question IDs and two answers and I'm trying to match the two answers with the two answers from the form submission.
I'm not sure what I'm doing wrong.
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
//Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc,$_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc,$_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc,$_POST['question1']);
$question2 = mysqli_real_escape_string($dbc,$_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if (($answer == $answer1Post) && ($answer == $answer2Post)) {
} else {
$errors = true;
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => $errors, 'message' => $message);
}
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
//Output the result
$output = json_encode($output);
echo $output;
?>
Since your question is not clear in the first place, so I'm assuming that the question you are asking is "why you're not getting any matching results, when you've the correct answers in the database?". Please correct me, if this is wrong.
The logic can be like this:-
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
// Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc, $_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc, $_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc, $_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc, $_POST['question1']);
$question2 = mysqli_real_escape_string($dbc, $_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc, $query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if ($answer == $answer1Post) {
// The first answer is correct
$errors = false;
$message = "Your first answer is correct!";
} else if ($answer == $answer2Post) {
// The second answer is correct
$errors = false;
$message = "Your second answer is correct!";
} else {
$errors = true;
$message = "Your answers did not match the answers inside the
}
$output = array('errorsExist' => $errors, 'message' => $message);
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
// Output the result
$output = json_encode($output);
echo $output;
?>
It's better to have more segregation of logical conditions. In this case, it's your two answers to check for.
Hope it helps.
How do I check if username or email exists and then put a error message in my error array. Right now i have:
$sql = "SELECT username, email FROM users WHERE username = '" . $username . "' OR email = '" . $email . "'";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0)
{
echo "That username or email already exists";
}
But I want to check if it is the username OR the email that is existing and then put:
error[] = "username is existing"; //if the username is existing
error[] = "email is existing"; //if the email is existing
How to do?
It would be easier if you just did a quick true/false check in the SQL and checked the flag that came back.
$sql = "SELECT "
. "(SELECT 1 FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "'), "
. "(SELECT 1 FROM `users` WHERE `email` = '" . mysql_real_escape_string($email) . "')";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$foundFlags = mysql_fetch_assoc($query);
if ($foundFlags['username']) {
$error[] = "username is existing";
}
if ($foundFlags['email']) {
$error[] = "email is existing";
}
} else {
// General error as the query should always return
}
When it does not find an entry, it will return NULL in the flag, which evaluates to false, so the if condition is fine.
Note that you could generalise it for a field list like this:
$fieldMatch = array('username' => $username, 'email' => $email);
$sqlParts = array();
foreach ($fieldMatch as $cFieldName => $cFieldValue) {
$sqlParts[] = "(SELECT 1 FROM `users` WHERE `" . $cFieldName . "` = '" . mysql_real_escape_string($cFieldValue) . "')";
}
$sql = "SELECT " . implode(", ", $sqlParts);
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$foundFlags = mysql_fetch_assoc($query);
foreach ($foundFlags as $cFieldName => $cFlag) {
if ($foundFlags[$cFieldName]) {
$error[] = $cFieldName . " is existing";
}
}
} else {
// General error as the query should always return
}
NB. Note that assumes all fields are strings, or other string-escaped types (eg. date/time).
Sounds like you're trying to let users know whether a username or email already exists at registration time. Here's what you can do:
<?php
//----------------------------------------
// Create first query
$usernameQuery = 'SELECT username FROM users WHERE username="'.mysql_real_escape_string($username).'"';
//----------------------------------------
// Query db
$usernameResult = mysql_query($userNameQuery);
//----------------------------------------
// Check if result is empty
if(mysql_num_rows($usernameResult) > 0){
//----------------------------------------
// Username already exists
$error[] = 'Username already exists';
//----------------------------------------
// Return error to user and stop execution
// of additional queries/code
} else {
//----------------------------------------
// Check if email exists
//----------------------------------------
// Create query
$emailQuery = 'SELECT email FROM users WHERE email="'.mysql_real_escape_string($email).'"';
//----------------------------------------
// Query the db
$emailResult = mysql_query($emailQuery);
//----------------------------------------
// Check if the result is empty
if(mysql_num_rows($emailResult) > 0){
//----------------------------------------
// Email already exists
$error[] = 'Email already exists';
//----------------------------------------
// Return error to user and stop execution
// of additional queries/code
} else {
//----------------------------------------
// Continue with registration...
}
}
?>
Please note that you should always escape your values before executing the actual query.
Additional Resources:
http://us.php.net/manual/en/function.mysql-real-escape-string.php
http://us.php.net/manual/en/function.mysql-escape-string.php
You can fetch one row and see if you got same email that you search or same username or both. You can do LIMIT 0,1 if you can stop after finding first row matching either this or that.