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
));
Related
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
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();
if(isset($_GET['id'])){
$nome = $_GET['nome'];
$cognome = $_GET['cognome'];
$id = $_GET['id'];
$sql = "UPDATE utenti SET nome = :nome, cognome = :cognome WHERE id = :id";
$req = $dbh->prepare($sql);
$req->execute(
array(
":nome" => $nome,
":cognome" => $cognome,
":id" => $id,
)
);
} else {
$nome = $_GET['nome'];
$cognome = $_GET['cognome'];
$sql = "INSERT INTO utenti (nome, cognome) VALUES (:nome, :cognome)";
$req = $dbh->prepare($sql);
$req->execute(
array(
":nome" => $nome,
":cognome" => $cognome,
)
);
}
Hello everyone. I have this code that inserts or updates a form's data within a database. I would like to include an "if" check that you are checking that the user does not already exist in the database. How can I do? Thank you
Try this:
$nome = $_GET['nome'];
//Searching the nome in the database
$req = $dbh->prepare("SELECT COUNT(*) AS anzahl FROM user WHERE Benutzername = :nome");
//Counts the rows with the given nom
$req->bindParam(':nome', $nome, PDO::PARAM_STR);
$req->execute();
$result = $req->fetch();
if ($result[0] > 0) {
//already exists - A row was found
echo "Already exists";
}
else {
//not existing - There was no row with that username
"Your Insertquery, use $req2 here"
}
Edit 2: This should work now ^^
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";
}
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...