Duplicate Check of email field using php - php

i am new at php. i want to know that how i can add duplicate check on my email field.
function email_exists($email){
global $db;
$query = "SELECT email FROM student";
$statement = $db->prepare($query);
$statement->execute();
$results = $statement->fetchAll();
foreach ($results as $key => $result) {
if ($result['email'] == $email){
return true;
}
}
return false;
}
i made this function and it works but i have a problem that when i update only name of my form.php and if the email remains same in the field it gives error. i want to know how i can solve this problem, if i only update name and not the email.

Try this query:
$sql = "SELECT email, COUNT(*) AS count FROM student GROUP BY email HAVING count > 0 ORDER BY count DESC;";

Please try this :
// #param email, id of updating record
function email_exists($email, $id){
global $db;
$query = "SELECT email FROM student WHERE id !=".$id;
$statement = $db->prepare($query);
$statement->execute();
$row_count = $statement->num_rows;// get total number of rows
if($row_count > 0)
{
// record exists
return true;
}
return false;
}

function email_exists($email){
global $db;
$query = "SELECT email FROM student WHERE email=:email";
$stmt = $db->prepare($query);
$stmt->bindParam(":email", $email);
$stmt->execute();
if ($stmt->rowCount() > 0) {
return true;
} else {
return false;
}
}

Related

How to fetch and return query results?

I am creating a function that is suppose to get the first name and last name from the database and return the query. Something is not right about it though.
The first and last names don't show up. I'm not getting any errors or warnings and I've tried all of the answers provided on this site and others(there is not much though).
Can someone tell me what is wrong with it ?
public function getFirstAndLastName() {
$username = $this->user['username'];
$query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? ");
$query->bind_param("s", $username);
$query->execute();
$query_result = $query->get_result();
$query_result->fetch_array();
while ($row = $query_result->fetch_assoc()) {
$row['first_name'];
}
return $row;
}
First of all if you are trying to finding a better way you can use this one
public function getFirstAndLastName() {
$username = $this->user['username'];
$query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? ");
$query->bind_param("s", $username);
$query->execute();
$query_result = $query->get_result();
$result = $query_result->fetch_all(MYSQLI_ASSOC);
Return $result;
}
mysqli has a handy function that instantly returns an array from the query result: mysqli_fetch_all(). So instead of this lines
while ($row = $query_result->fetch_assoc()) {
$row['first_name'];
}
it could be just a single line:
$result = $query_result->fetch_all(MYSQLI_ASSOC);
if you are looking to finding the answer why your function will return null i will explain for you :
There is some mistake in your codes
first of all when you execute this line $query_result->fetch_array();
actually you just make empty the mysqli buffer! so you don't have anything in buffer to catch it in this line -> while ($row = $query_result->fetch_assoc()) {
and in other hand even if you had something in buffer then you dont do nothing in this line ->
$row['first_name'];
if you are looking to correct your codes you should write the code like this ->
first of all make comment this line -> $query_result->fetch_array();
public function getFirstAndLastName() {
$username = $this->user['username'];
$query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? ");
$query->bind_param("s", $username);
$query->execute();
$query_result = $query->get_result();
//$query_result->fetch_array();
while ($row = $query_result->fetch_assoc()) {
$result[] = $row['first_name'];
}
return $result;
}
Edit:
if you are looking to get both first name and last name you have to do like this ->
public function getFirstAndLastName() {
$username = $this->user['username'];
$query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? ");
$query->bind_param("s", $username);
$query->execute();
$query_result = $query->get_result();
//$query_result->fetch_array();
while ($row = $query_result->fetch_assoc()) {
$result[] = $row;
}
return $result;
}
Try with $query->bind_param(":username", $username)
and change in the query the ? by :respuesta
"SELECT first_name, last_name FROM users WHERE username = :username
Looks the docs and apologies for my poor english
https://www.php.net/manual/es/pdostatement.bindparam.php

SELECT query with bindParam returns nothing

public function showSingleVisit(){
//echo $this->doctorID; the printed 1111
//$this->doctorID = 1111;
$db = connect_db();
$query = "SELECT * FROM visit WHERE doctorID = :doctorID";
$result = $db->prepare($query);
$result->bindParam(':doctorID', $this->doctorID);
$result->execute();
return $result;
}
This query doesn't return any row but when putting $this->doctorID = 1111 I get the rows that is wanted. I use bindParam in INSERT query in this class and works correctly. What's the problem?
UPDATE:
class visit{
//define public varibles
public function showSingleVisit(){
$db = connect_db();
$query = "SELECT * FROM visit WHERE visit = 0 AND doctorID = :doctorID AND patientID = :patientID";
$result = $db->prepare($query);
$result->bindParam(':patientID', $this->patientID);
$result->bindParam(':doctorID', $this->doctorID);
$result->execute();
return $result;
}
}
Here's how I call the function un the other page:
$visit = new visit;
$visit->doctorID = $auth->user->IDNo;
$visit->caseNo = $_SESSION['caseNo'];
$result = $visit->showSingleVisit();
if($result){
while($row = $result->fetch()){
echo'<p>
<label>Date:</label>
<span>'.$row->visitDate.'</span>
</p>';
}
}
else{
echo "No exists!";
}
Neither it shows any dates, nor it prints "No exists!".
you have to specify the type of the param :
$result->bindParam(':doctorID', $this->doctorID, PDO::PARAM_INT);
look at here :
http://php.net/manual/fr/pdostatement.bindparam.php
since doctorID is integer, you should add data_type to INT. it look like this
$result->bindParam(':doctorID', $this->doctorID, PDO::PARAM_INT);

Check to see if row exists

I have a form and when submitted, data will be inserted into three tables (user, journey, user_journey tables). Before the data is inserted, I want to check if that user already exists in the user table. If not, then there is no problem, the user will be inserted into the user table, however, if the user already exists in the user table, I don't want to add the user again. I want to get the user's user_id and insert into the third table (user_journey).
At the moment, when I submit the form, the user is inserted into the user table even if they exist in the table already.
I'm not sure about the way I went about checking if the user exists is correct and the way I'm fetching the user_id. Any advice would be appreciated
$query = $db->query("SELECT COUNT(*) FROM user WHERE facebook_id = '.$hdnFacebookId.'");
//$query->execute();
//$countRows = $query->rowCount();//return number of rows
//check to see if user is already in the database
if ($query->fetchColumn() > 0)
{
if ($oneWay)
{
$query_journey = $db->prepare("INSERT INTO journey
(from_destination,to_destination,journey_type,depart_date,depart_time,seats_available,journey_message,user_type)
VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime','$seatcounter','$textareanotes','$radUserType')");
}
else
{
$query_journey = $db->prepare("INSERT INTO journey
(from_destination,to_destination,journey_type,depart_date,depart_time,return_date,return_time,seats_available,journey_message,user_type)
VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime',STR_TO_DATE('$returnDate','%d/%m/%Y'),'$newRetTime ','$seatcounter','$textareanotes','$radUserType')");
}
$user_query = $db->prepare("SELECT user_id FROM user WHERE facebook_id = '$hdnFacebookId'");
$result = $user_query->execute();
$user_query_result = $user_query->fetch(PDO::FETCH_ASSOC);
$query_journey->execute();//EXECUTE QUERY
$lastJourneyID = $db->lastInsertId();
$queryUserJourney = $db->prepare("INSERT INTO user_journey
(journey_id,user_id)
VALUES('$lastJourneyID','$user_query_result')");
$queryUserJourney->execute();//EXECUTE QUERY
//include('index.php');
}
else //insert user
{
//if $oneWay true, then omit $returnDate and $returnTime
if ($oneWay)
{
$query = $db->prepare("INSERT INTO journey
(from_destination,to_destination,journey_type,depart_date,depart_time,seats_available,journey_message,user_type)
VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime','$seatcounter','$textareanotes','$radUserType')");
}
else
{
$query = $db->prepare("INSERT INTO journey
(from_destination,to_destination,journey_type,depart_date,depart_time,return_date,return_time,seats_available,journey_message,user_type)
VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime',STR_TO_DATE('$returnDate','%d/%m/%Y'),'$newRetTime ','$seatcounter','$textareanotes','$radUserType')");
}
$queryfb = $db->prepare("INSERT INTO user
(facebook_id,facebook_username,facebook_first_name,facebook_last_name,facebook_image,facebook_link)
VALUES('$hdnFacebookId','$hdnUsername','$hdnFirstName','$hdnLastName','$hdnFacebookImg','$hdnFacebookUrl')");
$query->execute();
$lastUserID = $db->lastInsertId();
$queryfb->execute();
$lastJourneyID = $db->lastInsertId();
$queryUserJourney = $db->prepare("INSERT INTO user_journey
(user_id,journey_id)
VALUES('$lastJourneyID','$lastUserID')");
$queryUserJourney->execute();
}
UPDATED
function userExists($db, $hdnFacebookId)
{
$userQuery = "SELECT * FROM user WHERE facebook_id = :user;";
$stmt = $db->prepare($userQuery);
$stmt->execute(array(':user'=>$hdnFacebookId));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
return true;
}
return false;
}
$userExists = userExists($db,$hdnFacebookId);
if($userExists)
{
//don't insert user
//get user's id from database
$user_query = $db->prepare("SELECT * FROM user WHERE facebook_id = '$hdnFacebookId'");
$result = $user_query->execute();
$user_query_result = $user_query->fetch(PDO::FETCH_ASSOC);
$userID = $user_query_result['user_id'];
$query_journey->execute();//EXECUTE QUERY
$lastJourneyID = $db->lastInsertId();
$queryUserJourney = $db->prepare("INSERT INTO user_journey
(journey_id,user_id)
VALUES('$lastJourneyID','$userID')");
$queryUserJourney->execute();//EXECUTE QUERY
}
else
{
//insert user
}
A typical "Check if user exists":
function userExists($db, $user)
{
$userQuery = "SELECT * FROM users u WHERE u.user=:user;";
$stmt = $db->prepare($userQuery);
$stmt->execute(array(':user' => $user));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
return true;
}
return false;
}
So you can do something like
$user = isset($_POST['user']) ? $_POST['user'] : "Unknown";
$userExists = userExists($db, $user);
if($userExists)
{
// Don't insert
]
else
{
// Insert the user.
}

Calling PDO query within a function

I'm 'doomsday' (mysql_ depreciation!) prepping some of my older applications that take the use of mysql_ extentions. I am currently converting them into PDO.
I use a lot of functions to make my work easy. However I cant get the $db->query within a function to work. For example I'm converting this function:
function GetAccount($account_id){
$Query = mysql_query("SELECT name, balance, account_number FROM accounts WHERE id = '$account_id'");
if (mysql_num_rows($Query) > 0){
$Result = mysql_fetch_assoc($Query);
return $Result;
} else {
return false;
}
}
Into this PDO function.
function GetAccount($account_id){
global $db;
$Result = $db->query("SELECT name, balance, account_number FROM accounts WHERE id = '$account_id'");
if (count($Result) > 0){
return $Result;
} else {
return false;
}
}
I have established a PDO connection outside of this function, which works fine with queries outside of any function.
The problem for the second (PDO) function is that the $Result is empty. A var_dump returs: bool (false).
What am I forgetting/doing wrong?
Thank you :)
Fixed it, new function:
function GetAccount($account_id){
global $db;
$Result = $db->prepare("SELECT name, balance, account_number FROM accounts WHERE id = '$account_id'");
$Result->execute();
$Result = $Result->fetch();
if (count($Result) > 0){
return $Result;
} else {
return false;
}
}
The only thing I did was :
$Result->prepare("query stuff");
$Result->execute();
$Result = $Result->fetch();

convert mysql to PDO statement

This is the login function written using MySQL way
However, the problem exists when it convert into PDO way
MYSQL:
<?
function confirmUser($username, $password){
global $conn;
if(!get_magic_quotes_gpc()) {
$username = addslashes($username);
}
/* Verify that user is in database */
$q = "select UserID,UserPW from user where UserID = '$username'";
$result = mysql_query($q,$conn);
if(!$result || (mysql_numrows($result) < 1)){
return 1; //Indicates username failure
}
/* Retrieve password from result, strip slashes */
$dbarray = mysql_fetch_array($result);
$dbarray['UserPW'] = stripslashes($dbarray['UserPW']);
$password = stripslashes($password);
/* Validate that password is correct */
if($password == $dbarray['UserPW']){
return 0; //Success! Username and password confirmed
}
else{
return 2; //Indicates password failure
}
}
PDO:
<?
function confirmUser($username, $password){
global $conn;
include("connection/conn.php");
$sql = '
SELECT COALESCE(id,0) is_row
FROM user
WHERE UserID = ?
LIMIT 1
';
$stmt = $conn->prepare($sql);
$stmt->execute(array('09185346d'));
$row = $stmt->fetch();
if ($row[0] > 0) {
$sql = '
SELECT COALESCE(id,1) is_row
FROM user
WHERE UserPW = ?
LIMIT 1
';
$stmt = $conn->prepare($sql);
$stmt->execute(array('asdasdsa'));
$row = $stmt->fetch();
if ($row[0] > 0)
return 2;
else
return 0;
}
elseif ($row[0] = 0)
{return 1;}
}
What is the problem ?? And is it necessary to include bind parameter in PDO??? THANKS
Aside from your use of global and your include inside the function (you should investigate an alternative way of structuring your function not to do this), I would change the code as follows:
$sql =
'SELECT id
FROM user
WHERE UserID = ?
AND UserPW = ?
LIMIT 1';
$stmt = $conn->prepare($sql);
$stmt->execute(array(
'09185346d',
'asdasdsa'
));
if ($stmt->rowCount() == 1) {
return 0;
}
else {
return 1;
}
Combing the queries to give a general Authentication error, instead of allowing people to trial valid usernames, and then valid passwords, and then using PDOStatements rowCount method do see if your row was returned.
To answer your second part, it is not necessary to specifically use bindParam to prevent SQL injection.
Here's a quick example of the difference between bindParam and bindValue
$param = 1;
$sql = 'SELECT id FROM myTable WHERE myValue = :param';
$stmt = $conn->prepare($sql);
Using bindParam
$stmt->bindParam(':param', $param);
$param = 2;
$stmt->execute();
SELECT id FROM myTable WHERE myValue = '2'
Using bindValue
$stmt->bindValue(':param', $param);
$param = 2;
$stmt->execute();
SELECT id FROM myTable WHERE myValue = '1'

Categories