Check record exists db - error show - php

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.

Related

I want to implement something that doesn't allow the user to rate more than once

I have used someone else's code that uses the ipaddress way. However, I would like to use a code that checks for the current userid and the id number.
$ipaddress = md5($_SERVER['REMOTE_ADDR']); // here I am taking IP as UniqueID but you can have user_id from Database or SESSION
/* Database connection settings */
$con = mysqli_connect('localhost','root','','database');
if (mysqli_connect_errno()) {
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
} /* end of the connection */
if (isset($_POST['rate']) && !empty($_POST['rate'])) {
$rate = mysqli_real_escape_string($con, $_POST['rate']);
// check if user has already rated
$sql = "SELECT `id` FROM `tbl_rating` WHERE `user_id`='" . $ipaddress . "'";
$result = mysqli_query( $con, $sql);
$row = mysqli_fetch_assoc();//$result->fetch_assoc();
if (mysqli_num_rows($result) > 0) {
//$result->num_rows > 0) {
echo $row['id'];
} else {
$sql = "INSERT INTO `tbl_rating` ( `rate`, `user_id`) VALUES ('" . $rate . "', '" . $ipaddress . "'); ";
if (mysqli_query($con, $sql)) {
echo "0";
}
}
}
//$conn->close();
In your database table, set the user_id column as UNIQUE KEY. That way, if a user tries to cast a second vote, then the database will deny the INSERT query and you can just display a message when affected rows = 0.
Alternatively, (and better from a UX perspective) you can preemptively do a SELECT query for the logged in user before loading the page content:
$allow_rating = "false"; // default value
if (!$conn = new mysqli("localhost", "root","","database")) {
echo "Database Connection Error: " , $conn->connect_error; // never show to public
} elseif (!$stmt = $conn->prepare("SELECT rate FROM tbl_rating WHERE user_id=? LIMIT 1")) {
echo "Prepare Syntax Error: " , $conn->error; // never show to public
} else {
if (!$stmt->bind_param("s", $ipaddress) || !$stmt->execute() || !$stmt->store_result()) {
echo "Statement Error: " , $stmt->error; // never show to public
} elseif (!$stmt->num_rows) {
$allow_rating = "true"; // only when everything works and user hasn't voted yet
}
$stmt->close();
}
echo "Rating Permission: $allow_rating";
And if they already have a row in the table, then don't even give them the chance to submit again.

check username in databse and update[html,mysql,php]

i have been trying since yesterday, and almost covered all questions regarding this matter in Stackoverflow plus googling, but so far nothing is working with me, i try to check username availability before updating the username in database, however, it wont check and always update the username directly without error message regarding not availability of the name..
here my code
//new connection
$con = new mysqli("localhost", "student", "student", "C14D5");
if ($con->connect_errno) { //failed
echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}
//success
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['clientN'])) {
$query = mysqli_query("SELECT client_name FROM clients WHERE client_name='".$_POST['clientN']."'");
if (mysqli_num_rows($query) != 0) {
echo "<script>
alert('Username is not available, please select another username.');
</script>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
// run sql
$sql ="UPDATE `clients` SET `client_name` = '".$_POST['clientN']."' WHERE `client_ID` = '".$_POST['SelectClient']."'";
if ($con->query($sql) === TRUE) {
echo "<h3> New record created successfully</h3>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
echo "Error : " . $sql . "<br>" . $con->error;
}
$con->close();
}
}
You can use the mysqli_num_rows() function to avoid data duplication in your database
use this code :
//specify the database connection factors as usual ,then
$uname = $_POST['your_username_field'];
$sql = "SELECT * FROM your_db where username='$uname'";
//the variable 'sql' will store the resultset of the query
$num_row = mysqli_num_rows($sql);
// the 'num_row' will store the number of rows which matches your $sql resultset. So if it is greater than '0' then the data already exists
if( $num_row > 0)
{
// display 'username exists error'
}
else
{
// Insert user name into your database table
}
If the num_rows is greater than 0 ,then the username is already present in your database table . So at that case throw error. else INSERT the user name into your database and display success message .

Query Checking for Existence - PHP

I'm trying to to test to see if an email address exists in my database by running a query check.
I can connect to the database fine.
However no matter what, even if the email exists it returns "doesn't exist".
<?php
//----------------------------------------------------------------------------------//
//Setup
require_once('SB_Constants.php');
//----------------------------------------------------------------------------------//
//Connect to the database
//----------------------------------------------------------------------------------//
$connection = mysqli_connect(DATABASE_HOST, SAVE_USERNAME, SAVE_PASSWORD, DATABASE_NAME);
// check the connection was successful
if (mysqli_connect_errno($connection)) {
header('HTTP/1.0 500 Internal Server Error', true, 500);
die(FailedToAccessDatabase . ". Failed to connect to Database");
} else {
echo "Connection Success!";
}
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT email_address FROM assessorID WHERE email_address = 'ryan#ablah.com'");
if (mysqli_num_rows($query_identifier) == 0) {
die(UnregisteredAssessor . ". Doesn't Exist");
} else {
// Exists
echo "Exists getting ace id.";
//Get the assessor ID
$result = mysqli_query($connection, "SELECT ace_id FROM assessorID WHERE email_address = 'ryan#blah.com'");
echo $result;
}
/* close connection */
mysqli_close($connection);
?>
Any ideas of the problem? :)
Various mistakes. Fix:
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = 'ryan#ablah.com'");
if (mysqli_num_rows($assessorEmail) == 0) {
die(UnregisteredAssessor . ". Doesn't Exist");
} else {
// Exists
echo "Exists getting ace id.";
//Get the assessor ID
$result = mysqli_fetch_assoc($assessorEmail);
echo $result['ace_id'];
}
Your problem is mysqli_num_rows($query_identifier) is accessing an undefined variable instead of $assessorEmail.
Additionally, you only need one query if you just want the ace_id:
$assessorEmail = mysqli_query($connection, "SELECT ace_id FROM assessorID WHERE email_address = 'ryan#ablah.com'");
If mysqli_num_rows($assessorEmail) returns a row, than the email exists and you already have the ace_id
while(mysqli_fetch_assoc($assessorEmail) = $row) {
echo $result['ace_id'];
}

PHP/MySQL log in system -

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.

PDO ->query returns null

$dbh->query works on $queryUser = $dbh->query, but not on $querySessions = $dbh->query, $querySessions is null,
echo $querySessions == null; echos 1
and then
Fatal error: Call to a member function fetchAll() on a non-object in
/path/to/file.php on line (while(count($querySessions->fetchAll()) !=
0))
if($_POST['loginbtn'])
{
$User = $_POST['user'];
$Pass = md5(md5("salt" . $_POST['pass'] . "salt2"));
if($User)
{
if($_POST['pass'])//not $Pass because thats hashed
{
$queryUser = $dbh->query("SELECT * FROM `Users` WHERE `UserName` = '" . base64_encode($User) . "' LIMIT 1");
$Record = $queryUser->fetch();
if($Pass != $Record["Password"])
{
echo "Incorect password.";
}
else
{
if($Record["Banned"] == 1)
{
echo "Sorry, your banned.";
}
else
{
if($Record["NeedsActivation"] == 1)
{
echo "You must activate your account before you can login.";
}
else
{
$SID = md5(rand(0,0x7fffffff) . "salt3");
$querySessions = $dbh->query("SELECT * FROM `Sessions` WHERE `ID` = " . $SID . " LIMIT 1");
echo $querySessions == null;
while(count($querySessions->fetchAll()) != 0)
{
$SID = md5(rand(0,0x7fffffff) . "salt2");
$querySessions = $dbh->query("SELECT * FROM `Sessions` WHERE `ID` = " . $SID . " LIMIT 1");
}
$_SESSION['id'] = $SID;
$dbh->query("INSERT INTO `godzchea_Site`.`Sessions` (`ID` ,`UserID`)VALUES ('" . $SID . "', '" . $Record["ID"] . "');");
echo base64_decode($Record["UserName"]) . " Logged in.";
}
}
}
}
else
{
echo "You must enter your password.";
}
}
else
{
echo "You must enter your username.";
}
}
can any of you see why its being set to null,
and if there's a better way to loop till I get a empty id.
The problem stand in the fact that that query, the one associated to $querySession is being a failure. Probably there's an error in your query because what the Manual say is:
PDO::query() returns a PDOStatement object, or FALSE on failure.
I'm not sure, but it also could be that no rows has been found.
A suggestion I could give to you, to find out what's the real errors is:
You put all of your PDO code inside a try catch block like: try{/*code in here*/}catch(PDOException $e){ exit($e->getMessage()); } and see what it output.
Take the query and the value of $SID and try to run it into phpmyadmin, directly into the database.
Note that the fatal error is also related to the fact that your query is returning false instead of an object. That errors just say that you are treating $querySession as an object but it is not.
For more information just leave a comment and I'll answer.
Good luck.

Categories