Trying to create update profile page in PHP PDO - php

I am trying to create an update profile page in PHP. But, I keep running into an error. When I submit the form to update the profile, there are four fields. Username, email, firstname, and lastname. Say I want to change only the first name of the user, when I submit the form, it gives me an error telling me the username/email/lastname is taken because that was already auto-filled in.
Here is my update profile form, the fields contain user information pulled from the database
Here is my update profile code that goes along with the form
// Queries
if (isset($_POST['userprofileupdate'])) {
$firstname = mysqli_real_escape_string($conn, $_POST['name_1']);
$lastname = mysqli_real_escape_string($conn, $_POST['name_2']);
$email = mysqli_real_escape_string($conn, $_POST['email_1']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
// Check if Email exists
$stmt = $pdo->prepare('SELECT * FROM `users` WHERE `email` = :email ');
$stmt->bindParam(":email", $email, PDO::PARAM_STR);
$stmt->execute();
$Count = $stmt->rowCount();
// Check if username exists
$stmt = $pdo->prepare('SELECT * FROM `users` WHERE `username` = :username ');
$stmt->bindParam(":username", $username, PDO::PARAM_STR);
$stmt->execute();
$Count1 = $stmt->rowCount();
if ($Count < 1) {
if ($Count1 < 1) {
$query = "UPDATE users SET username=?, firstname=?, lastname=?, email=? WHERE id=?";
$stmt = $pdo->prepare($query);
$stmt->bindParam('ssssi', $username, $firstname, $lastname, $email, $id);
$stmt->execute();
unset($_SESSION['username']);
unset($_SESSION['firstname']);
unset($_SESSION['lastname']);
unset($_SESSION['role']);
unset($_SESSION['email']);
unset($_SESSION['password']);
session_destroy();
header('Location: /panel/login?profile_changed');
} else {
header('Location: /panel/profile?username_taken');
}
} else {
header('Location: /panel/profile?email_taken');
}
}

$stmt = $pdo->prepare("SELECT * FROM users WHERE `email`=':email'");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();
/// update
$sql = "UPDATE users SET username=?, firstname=?, lastname=?, email=?
WHERE id=?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$firstname, $lastname, $email, $id]);
or please read fully this article for complete understand
https://phpdelusions.net/pdo_examples/select

Related

delete a record from the specified table in MySQL with PHP

I'm working on a registration form with MySQL and PHP, I have 2 table in MySQL: users and a_codes.
before I defined and insert some username into the a_codes table.
when a user enters a username in the registration form.it's checked with records in the a_codes table, if exist then registration done.
my problem is that I want after the user successfully registered, the mentioned username in the a_codes table must be deleted.
everything in my code below worked fine. the only question is how to delete the used username in the a_codes table?
. I'm new in PHP and thanks for any help.
<?php
require_once 'DbConnect.php';
//an array to display response
$response = array();
if(isset($_GET['apicall'])){
switch($_GET['apicall']){
case 'signup':
//checking the parameters required are available or not
if(isTheseParametersAvailable(array('username','email','password','gender'))){
//getting the values
$username = $_POST['username'];
$email = $_POST['email'];
$password = md5($_POST['password']);
$gender = $_POST['gender'];
//checking if the user is already exist in a_codes table with this username
$stmt = $conn->prepare("SELECT id FROM a_codes WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
//if the user already exist in the database
if($stmt->num_rows > 0){
//if user is already exist creating an insert query
$stmt = $conn->prepare("INSERT INTO users (username, email, password, gender) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $username, $email, $password, $gender);
//if the user is successfully added to the database
if($stmt->execute()){
//fetching the user back
$stmt = $conn->prepare("SELECT id, id, username, email, gender FROM users WHERE username = ?");
$stmt->bind_param("s",$username);
$stmt->execute();
$stmt->bind_result($userid, $id, $username, $email, $gender);
$stmt->fetch();
$user = array(
'id'=>$id,
'username'=>$username,
'email'=>$email,
'gender'=>$gender
);
$stmt->close();
//adding the user data in response
$response['error'] = false;
$response['message'] = 'done';
$response['user'] = $user;
}
} else {
$response['error'] = true;
$response['message'] = 'already registered';
$stmt->close();
}
}else{
$response['error'] = true;
$response['message'] = 'error eccoured';
}
break;
The correct syntax for mysql delete is;-
DELETE FROM table_name WHERE column = value;
in your case it will be
DELETE FROM `a_codes` WHERE `username` = "insert the username here"
or
$stmt = $conn->prepare("DELETE FROM a_codes WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();

How to generate token and create a url to send to email

I am trying to write a script for a student registration page, where a student enters his/her student id and if it exists then retrieve his/her email and generate a token and insert the token into the database and then send a registration url link with token and id to the student's email..how would i get that since i am a beginner in php and mysql.
where am i going wrong here?
<?php
error_reporting(1);
session_start();
include 'includes/connect.php';
include 'includes/tokengenerator.php';
if ($_POST["Submit"] == "Submit") {
$stu_id = $_POST['stu_id'];
$sql = "SELECT email FROM people WHERE stu_id = :stu_id";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':stu_id', $stu_id);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($result)) {
$email = $result['email'];
//echo $email;
//exit();
for ($i = 1; $i <= 2; $i++) {
$token = generateToken();
//echo $token;
$email = $result['email'];
$sql = "INSERT INTO students (token) VALUES ($token) WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':token' => $token,
));
$result1 = $stmt->fetch(PDO::FETCH_ASSOC);
}
} else {
echo 'Please Contact principal for student ID';
}
}
?>
You are binding the wrong value in the query: :token vs :email.
You should actually have 2 placeholders and bind both values.
$sql = "INSERT INTO students (token) VALUES (:token) WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':token' => $token,
':email' => $email
));
And as noted correctly by #Saty, you cannot have a WHERE clause on an INSERT statement:
$sql = "INSERT INTO students (token, email) VALUES (:token, :email)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':token' => $token,
':email' => $email
));
Or you might need an UPDATE statement instead of an INSERT:
$sql = "UPDATE students SET token = :token WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':token' => $token,
':email' => $email
));

Check if the email exists using pdo

This is the section I use to add users.
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: ./index.php");
}
require 'conn.php';
$message = '';
if(!empty($_POST['name']) &&!empty($_POST['email']) && !empty($_POST['password'])):
// Enter the new user in the database
$sql = "INSERT INTO users (name, email, password) VALUES (:name,:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':name', $_POST['name']);
$stmt->bindValue(':email', $_POST['email']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
?>
I personally do it by using a query and an if statement
$query = $conn->prepare("SELECT * FROM users WHERE email = :email");
$query->bindParam(':email', $_POST['email']);
if ($query->rowcount() = 0)
{
// insert account into database
}
else {
// display error message
}
To check if the email exists or not, you have to write a query whether that email is stored in the database. If the query result is not empty, you can show a message that the email exists. If the query result is empty, you can make him a new user.
For that you have to write this query
$sql="select name from user where email='$email'";
$stmt = $conn->prepare($sql);
if ($stmt->rowcount() = 0)
{
$sql = "INSERT INTO users (name, email, password) VALUES (:name,:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':name', $_POST['name']);
$stmt->bindValue(':email', $_POST['email']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
}
else {
$msg="Email already exists";
}

INSERT INTO SQL php Function does not work

I have managed to write a php script that checks if a username already exists in the database and only adds a new user if it does not already exist.
This is my php script:
<?php
require "init.php";
if(isset($_POST['username']) && isset($_POST['forename']) && isset($_POST['surname']) && isset($_POST['password'])){
$username = $_POST['username'];
$forename = $_POST['forename'];
$username = $_POST['surname'];
$password = $_POST['password'];
$stmt = "SELECT username FROM users WHERE username = ?";
$result = $dbcon -> prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->bind_result($username);
if($result->fetch()){
echo "Can't add new user as it already exists!";
}
else{
$stmt_two = "INSERT INTO users (username, forename, surname, password)
VALUES(?, ?, ?, ?)";
$result_two = $dbcon -> prepare($stmt_two);
$result_two->bind_param('ssss', $username, $forename, $surname, $password);
$result_two->execute();
$result_two->close();
echo json_encode("Success");
}
}
?>
I believe the records are not being inserted or being inserted intermittently due to the fact that I have more than one prepared statement. If I just do the INSERT INTO statement on its' own with the SELECT FROM statement - the records are added almost instantly.
Why is this and what is wrong with my code?
Thanks
Just as I have said in the comments, don't over complicate and just check the number of rows found. No need to fetch anything. You're just checking if that user exists anyway.
$stmt = "SELECT username FROM users WHERE username = ?";
$result = $dbcon->prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->store_result();
if($result->num_rows() > 0) { // if it exists
} else {
// make your insertions
}
And another note:
isset can take multiple arguments:
if(isset($_POST['username'], $_POST['forename'], $_POST['surname'], $_POST['password'])) {
// and so on
}
Edit: Another flavor (using COUNT() of MySQL):
$stmt = "SELECT COUNT(username) FROM users WHERE username = ?";
$result = $dbcon->prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->bind_result($count);
$result->fetch();
if($count > 0) { // exists
} else {
// do something else
}

Login script using PDO

I'm implementing a login script which isn't working correctly. I want users to be able to login with either their usernames or emails. I have two tables:
user - contains login information(username, password, email, isactive)
userprofile - contains profile information
ISSUES/ERRORS:
Logging in with the email addresses doesn't work.
If the username alone is entered, leaving the password field empty, the user is still logged in regardless.
THE CODE(isactive checks if a user's account has been activated after email verification)
$uname = htmlspecialchars($_POST['username']);
$pword = htmlspecialchars($_POST['password']);
$isActive = 1;
$getId = 0;
try{
$stmt = $db->prepare("SELECT * FROM user WHERE username = :username OR email = :email AND password = :password AND isactive = :isactive");
$stmt->execute(array(':username' => $uname, ':email' => $uname, ':password' => $pword, ':isactive' => $isActive));
$numrows = $stmt->fetch(PDO::FETCH_ASSOC);
//to enable me count number of rows returned
$number = $stmt->fetch(PDO::FETCH_NUM);
$_SESSION['username'] = $numrows['username'];
$getId = $numrows['Id'];//get the id of the user
}catch(PDOException $ex){
echo 'QUERY ERROR: ' . $ex->getMessage();
}
/*this checks to see that the user has a profile (userId is a foreign key, thus user.Id = userprofile.userId always)*/
try{
$query = $db->prepare("SELECT * from userprofile WHERE userId = :userId");
$query->execute(array(':userId' => $getId));
$row = $query->fetchAll();
}catch(PDOException $exc){
echo 'QUERY ERROR: ' . $exc->getMessage();
}
//Check results and log user in
if(count($number) == 1 && count($row) == 1){
header("Location: index.php");
}
else {$errorMessage = "<p style='color:#ff851b'>Invalid username or password</p>";}
What do i need to modify to get this working? Thanks
You can easily include the row count in your query as well:
And adjust the query :
SELECT *, count(*) AS numrows
FROM user
WHERE (username = :username OR email = :email) AND
password = :password AND isactive = :isactive
Please make the following changes:
$stmt->execute(array(':username' => $uname,
':email' => $uname,
':password' => $pword,
':isactive' => $isActive));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$row){
throw new Exception('User not found');
}
//get user data
$numrows = (int)$row['numrows'];
if($numrows === 1){
//found a user
$_SESSION['username'] = $row['username'];
$id = $row['Id'];
}
The main issue I see is this one; some brackets are needed:
Before:
$stmt = $db->prepare("SELECT * FROM user WHERE username = :username OR email = :email AND password = :password AND isactive = :isactive");
After:
$stmt = $db->prepare("SELECT * FROM user WHERE ((username = :username AND password = :password) OR (email = :email AND password = :password)) AND isactive = :isactive");
Also, in this line you are assigning $uname to username and email - possible copy/paste error here as well?
$stmt->execute(array(':username' => $uname, ':email' => $uname, ':password' => $pword, ':isactive' => $isActive));
Try
SELECT * FROM user WHERE (username = :username OR email = :email) AND password = :password AND isactive = :isactive"
as query... Should work...

Categories