I know this has been asked a lot, and I've search and literally tried it all. I'm really close, but can't get it to work.
I'm trying to check if the username or usermail is already in use and display the error accordingly.
<?php
if (isset($_POST['register'])) {
try
{
$checkValidity = $connect->prepare('SELECT username, usermail FROM users WHERE username = :username OR usermail = :usermail');
$checkValidity->bindValue(':username', $username);
$checkValidity->bindValue(':usermail', $usermail);
$checkValidity->execute();
$row = $checkValidity->fetchColumn();
if ($row == $username) {
$errName = 'This username is already taken.';
}
if ($row == $usermail) {
$errMail = 'Email already in use.';
}
}
catch(PDOException $e)
{
// print $e->getMessage();
}
}
?>
It works fine for the username, but for the life of me I can't get the email error to work...
I attempted separate SELECT queries (username/usermail), and the email error would show ONLY if the username error showed.
The email error will never show just by itself.
I've spent one too many hours just trying to get this to work, and I'm slowly losing my mind.
Any indication would be greatly appreciated...!
Thank you...
FetchColumn return first column value. You need to use fetch instead. Like
$row = $checkValidity->fetch();
if ($row['username'] == $username) {
$errName = 'This username is already taken.';
}
if ($row['usermail'] == $usermail) {
$errMail = 'Email already in use.';
}
There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data.
your fetching username only you need to use fetch() to get the whole row and compare like this
$row = $checkValidity->fetch();
if ($row['username'] == $username) {
$errName = 'This username is already taken.';
}
if ($row['useremail'] == $useremail) {
$errMail = 'Email already in use.';
}
Related
I'm new here so I hope I do this right.
I am having some problems with sending the right message from my php to my
html.
Here you can see the php part that sould give a message back if the username isn't valid(if is uses #$%^& etc.)
$validUsername = $CurrentUser->ValidateUsername($username);
//if the input isn't filled send a message back
if(!$validUsername)
{
$messageError = "Please fill in a valid username";
header("location: ../public/index.php?messageError=$messageError");
}
and another one that should check if the username is unique
$uniqueUsername = $CurrentUser->CheckAvailableUsername($validUsername);
if (!$uniqueUsername)
{
$messageError = "Please fill in a unique username";
header("location: ../public/index.php?messageError=$messageError");
}
now the weird thing is if use #$%^&etc. as a username it will give me back a please fill in a unique username instead of please fill in a valid username and I can't find out why.
oh btw I made a class named User with these methods Ill show them below here.
public function ValidateUsername($username)
{
if (!empty($username))
{
if (isset($username))
{
if (!preg_match("/^[a-zA-Z ]*$/", $username))
{
return false;
}
return $this->username = $username;
}
return false;
}
return false;
}
And the other one.
public function CheckAvailableUsername($username)
{
$sql = "SELECT * FROM `tbl_todolist`
WHERE `username` = '$username';";
$result = $this->dataBase->query($sql)->rowCount();
if ($result == 1)
{
return false;
}
return $this->username = $username;
}
I really hope you guys can help me with this.
After header(...); you need to throw in a return; or exit; to exit right there, otherwise it continues beyond that header.
Additional Notes
You are open to SQL injection in CheckAvailableUsername, you need to sanitize the value before you get to that function and also escape/bind the value to your query instead. It looks like you are using PDO already.
I'm trying to implement a duplicate topic blocking system to a forum script. Since I'm extremely poor about PHP I though maybe you'd like to help me. Unfortunately, I'm not even sure if I'm trying to edit the right part of the script but here's the code:
// If it's a new topic
if ($fid)
{
$subject = pun_trim($_POST['req_subject']);
if ($pun_config['o_censoring'] == '1')
$censored_subject = pun_trim(censor_words($subject));
if ($subject == '')
$errors[] = $lang_post['No subject'];
else if ($pun_config['o_censoring'] == '1' && $censored_subject == '')
$errors[] = $lang_post['No subject after censoring'];
else if (pun_strlen($subject) > 70)
$errors[] = $lang_post['Too long subject'];
else if ($pun_config['p_subject_all_caps'] == '0' && is_all_uppercase($subject) && !$pun_user['is_admmod'])
$errors[] = $lang_post['All caps subject'];
}
So I'm trying to implement if $subject is exist in DB (SELECT * FROM topics WHERE subject), show an error in this format: $errors[] = $lang_post['Topic is already exist'];
Thank you.
There are several ways of getting the information that it is in the database or not(here i'm using PDO)
This is the common code:
$conn = new PDO('mysql:dbname=db_name', 'username', 'password')
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
fetch->(PDO::FETCH_NUM)
$sql = $conn->prepare("query_to_db");
$sql->execute();
$rows = $sql->fetch(PDO::FETCH_NUM);
if( $row > 0 ){
echo "the credentials exists";
}
else{
// there is nothing like this in the database
}
mysql error code 23000
try{
// connection code above mentioned
$sql = $conn->prepare("query_to_db");
$sql->execute();
}
catch(PDOException $e){
if($e->getCode() == 23000){
// the credentials exists
}
else{
// doesn't exists
}
}
rowCount()
$sql = $conn->prepare("query_to_db");
$sql->execute();
$count = $sql->rowCount();
if($rowCount > 0){
//exists in the db
}
else{
//it doesn't exists in the db
}
But the rowCount doesn't in mysql
The php doc says:
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use DOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
I personally prefer the fetch->(PDO::FETCH_NUM) as it is more precise than the other.
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 am creating an part of a website that deals with confirmation of a user subscribing to a newsletter.
I am having trouble with the usage on prepared statements when selecting data.
This is basically a check against information that was sent to the user in an email and retrieved by getting the info from the entered url.
So there is a string or 'key' in the database that is sent to the user in an email as a link to a page on my site with the users details appended to the url. The script checks to see if these keys match
The problem is that when I run the script it will trigger an error. This says "wrong key".
The key in the database ($dbkey) is the same as the key provided in the email link. which is the same key that is made into $key. The problem though, is that in the while loop an error is being triggered and $dbkeyis not being passed the data from the database :
Notice: Trying to get property of non-object in C:\wamp\www\site\script.php on line 35
The sql statement when run in phpmyadmin does return the correct result set.
Here is the code:
$confirm= sanitize($_GET['confirm']);
$stmt = $link->prepare("SELECT id, dbkey FROM specials WHERE id = ?");
if (!$stmt)
{
$error = "{$link->errno} : {$link->error}";
include "$docRoot/html/main/error.html.php";
exit();
}
if (!$stmt->bind_param("i", $confirm))
{
$error = "{$stmt->errno} : {$stmt->error}";
include "$docRoot/html/main/error.html.php";
exit();
}
if (!$stmt->execute())
{
$error = "{$stmt->errno} : {$stmt->error}";
include "$docRoot/html/main/error.html.php";
exit();
}
$stmt->store_result();
if ($stmt->num_rows)
{
while ($row = $stmt->fetch())
{
$dbKey = $row->dbkey;
}
$key= sanitize($_GET['key']);
if ($dbKey !== $key)
{
echo 'wrong key';
}
}
else
{
echo 'not in database';
}
I would like to say that all other scripts connecting to the database in this manner do work, but this was the first time I have used prepared statements to select data. I wonder if this problem is caused by an error in my coding, hence the reason why I have posted this question.
If anyone could spot where I have gone wrong here, or possibly possibly provide some advice on how I would debug the code to see what exactly the error is that would be greatly appreciated!
Thanks!!
EDIT: The problem simply is the $key returns a string but $dbkey returns empty
EDIT2:
if ($stmt = $link->prepare("SELECT id, verified, dbkey FROM specials WHERE id=?")) {
$stmt->bind_param("i", $confirm);
$stmt->execute();
$stmt->bind_result($dbId, $dbVerified, $dbKey);
$stmt->fetch();
$stmt->close();
if ($dbKey !== $key)
{
echo 'wrong key';
}
else if ($dbVerified == 1)
{
echo 'already activated';
}
else if ($dbKey == $key && dbVerified == 0)
{
echo 'success';
}
}
else
}
echo 'user not in db';
}
$stmt->fetch() just returns a boolean indicating whether it was successful, not an object whose properties are the current row's fields. You need to call $stmt->bind_result() to specify into which variables you want the fields to be placed.
The approach taken in your second edit looks good, except that the test for whether the user is in the database should be onfetch(), not prepare() (or else use num_rows as you had previously). Thus:
if ($stmt = $link->prepare("SELECT id, verified, dbkey FROM specials WHERE id=?"))
{
$stmt->bind_param("i", $confirm);
$stmt->execute();
$stmt->bind_result($dbId, $dbVerified, $dbKey);
if ($stmt->fetch())
{
if ($dbVerified == 1)
{
echo 'already activated';
}
else if ($dbKey !== $key)
{
echo 'wrong key';
}
else if ($dbKey == $key && dbVerified == 0)
{
echo 'success';
}
}
else
}
echo 'user not in db';
}
$stmt->close();
}
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.