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
}
Related
This question already has answers here:
PDO query is always returning 1 or true
(2 answers)
Closed 3 years ago.
This code is a part of registration code. But it return always "Nickname already exist". I don't understand why.
if (isset($_POST['create'])) {
$nickname = $_POST['nickname'];
$email = $_POST['email'];
$password = $_POST['password'];
$slt1 = "SELECT nickname FROM users WHERE nickname='$nickname'";
$slt2 = "SELECT email FROM users WHERE email='$email'";
$stmt1 = $db->prepare($slt1);
$stmt2 = $db->prepare($slt2);
if($stmt1->execute([$nickname])) {
echo 'Nickname already exist';
} elseif ($stmt2->execute([$email])) {
echo 'email already exist';
} else {
//more code here
}
}
The way you use execute is wrong, and what an execute returns is a Boolean value (TRUE/FALSE) but not the number of rows your query has selected/affected.
So you need to get the count of the rows that your query affects and perform the "if" on that value.
Like this,
$stmt1->execute();
$number_of_rows = $stmt1->num_rows;
if($number_of_rows == 1){
echo 'Nickname already exist';
}
else{
//your code to insert data
}
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..
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';
}
Im trying to come up with MySQL logic for a search function I got on my page. Its a simple form where the user can choose to fill in search criteria. The criteria(s) is send as arguments to a function that generates the mysql logic. This is whats inside the PHP controller file:
case 'search':
if((empty($_POST['username'])) && (empty($_POST['firstname'])) && (empty($_POST['lastname']))
&& (empty($_POSt['agemin'])) && (empty($_POST['agemax'])) && (empty($_POST['country']))){
$members = get_all_username();
} else {
if(isset($_POST['username'])){
$otheruser = $_POST['username'];
} else { $otheruser = null; }
if(isset($_POST['agemin'])){
$ageMin = $_POST['agemin'];
} else { $ageMin = null; }
if(isset($_POST['agemax'])){
$ageMax = $_POST['agemax'];
} else { $ageMax = null; }
if(isset($_POST['country'])){
$country = $_POST['country'];
} else { $country = null; }
//if(isset($_POST['isonline']))
$members = search_members($otheruser, $ageMin, $ageMax, $country);
}
include('displaySearch.php');
break;
So if nothing is set a complete list of all the members is generated and displayed. This is the function that is called if any of the inputs is set:
function search_members($username, $ageMin, $ageMax, $country){
global $db;
$query = "SELECT username FROM profiles WHERE username = :username
AND age > :ageMin AND age < :ageMax AND country = :country";
$statement = $db->prepare($query);
$statement->bindValue(':username', $username); $statement->bindValue(':ageMin', $ageMin);
$statement->bindValue(':ageMax', $ageMax); $statement->bindValue(':country', $country);
$statement->execute();
if($statement->rowCount() >= 1){
return $statement->fetchAll();
} else {
return false;
}
}
The mysql logic is obviously wrong. I need a set of conditions (in the MySQL logic if possible) that checks the PHP variables for value and if there is none it should not be accounted for when querying the database. So if only the username is set in the form the other variables should not be included in the SQL logic.
I've looked up the MySQL IF() condition but Im still not able to come up with proper code that does what I need. If someone could point me in the right direction I would be able to do the rest myself. Any other approach for solving this kind of problem is also welcome.
If i understand your problem, then the simple way is to use if else to build sql query, for example
$sql = "SELECT username FROM profiles WHERE 1 "
if (!is_null($username)) {
$sql .= " AND username = :username ";
}
// All other checks
This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 7 months ago.
I am trying to create a user login/creation script in PHP and would like to know the best way to check if a username exists when creating a user. At the moment, I have the following code:
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$this->users = $server->query("SELECT * FROM user_list");
while ($check = mysql_fetch_array($this->users) {
if ($check['uname'] == $uname) {
What I'm not sure about is the best logic for doing this. I was thinking of adding a boolean variable to do something like (after the if statement):
$boolean = true;
}
if ($boolean) {
echo "User already exists!";
}
else {
$server->query("INSERT USER INTO TABLE");
echo "User added Successfully";
}
But this seems a little inefficient - is there a more efficient way to do this? Sorry if this has a basic solution - I'm a relatively new PHP programmer.
Use the WHERE clause to get only rows with the given user name:
"SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'"
Then check if the query results in selecting any rows (either 0 or 1 row) with MySQLi_Result::num_rows:
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$result = $server->query("SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'");
if ($result->num_rows() === 0) {
if ($server->query("INSERT INTO user_list (uname) VALUES ('".$server->real_escape_string($uname)."'")) {
echo "User added Successfully";
} else {
echo "Error while adding user!";
}
} else {
echo "User already exists!";
}
}
This basically involves doing a query, usually during validation, before inserting the member into the database.
<?php
$errors = array();
$alerts = array();
if (isset($_POST['register'])) {
$pdo = new PDO('[dsn]', '[user]', '[pass]');
// first, check user name has not already been taken
$sql = "SELECT COUNT(*) AS count FROM user_list WHERE uname = ?";
$smt = $pdo->prepare($sql);
$smt->execute(array($_POST['uname']));
$row = $smt->fetch(PDO::FETCH_ASSOC);
if (intval($row['count']) > 0) {
$errors[] = "User name " . htmlspecialchars($_POST['uname']) . " has already been taken.";
}
// continue if there are no errors
if (count($errors)==0) {
$sql = "INSERT INTO user_list ([fields]) VALUES ([values])";
$res = $pdo->exec($sql);
if ($res==1) {
$alerts[] = "Member successfully added.";
} else {
$errors[] = "There was an error adding the member.";
}
}
}
The above example uses PHP's PDO, so change the syntax to use whatever database abstraction you use.