wait please, dont post this as a duplicate because ive done research and tried everything but cant get it to work, i keep getting this error "Fatal error: Call to a member function prepare() on string in C:\wamp64\www\Etego\dbcontroller.php on line 63" i am trying to get people on my inscription form not to use the same email twice, thanks in advance! heres the code :
dbcontroller.php
<?php
class DBController {
public $host = "localhost";
public $user = "root";
public $password = "";
public $database = "members";
public $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
function updateQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query1: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function insertQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query2: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function deleteQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query3: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
}
/* Email already exists */
/*line 63*/
$db = new DBController;
$db->database->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
} else {
$error_message = "Email already exists";
}
//end of email existance
?>
index2.php
<!-- how to make members when login "keep me signed in" and ho to make users 13+ with the date input -->
<?php
if(!empty($_POST["register-user"])) {
/* Form Required Field Validation */
foreach($_POST as $key=>$value) {
if(empty($_POST[$key])) {
$error_message = "All Fields are required";
break;
}
}
/* Password Matching Validation */
if($_POST['password'] != $_POST['confirm_password']){
$error_message = 'Passwords should be same<br>';
}
/* Email Validation */
if(!isset($error_message)) {
if (!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) {
$error_message = "Invalid Email Address";
}
}
/* Validation to check if gender is selected */
if(!isset($error_message)) {
if(!isset($_POST["gender"])) {
$error_message = " All Fields are required";
}
}
/* Validation to check if Terms and Conditions are accepted */
if(!isset($error_message)) {
if(!isset($_POST["terms"])) {
$error_message = "Accept Terms and Conditions to Register";
}
}
if(!isset($error_message)) {
require_once("dbcontroller.php");
$db_handle = new DBController();
$query = "INSERT INTO members (username, firstname, lastname, password, email, gender, dob) VALUES
('" . $_POST["userName"] . "', '" . $_POST["firstName"] . "', '" . $_POST["lastName"] . "', '" . md5($_POST["password"]) . "', '" . $_POST["userEmail"] . "', '" . $_POST["gender"] . "' , '" . $_POST["dob"] . "' )";
$result = $db_handle->insertQuery($query);
if(!empty($result)) {
$error_message = "";
$success_message = "You have registered successfully!";
unset($_POST);
} else {
$error_message = "Problem in registration. Try Again!";
}
}
}
?>
<html>
<?php
include 'C:\wamp64\www\Etego\stylesignup.css';
?>
<head>
<title>https://Etego/signup.com</title>
</head>
<body>
<form name="frmRegistration" method="post" action="">
<table border="0" width="500" align="center" class="demo-table">
<?php if(!empty($success_message)) { ?>
<div class="success-message"><?php if(isset($success_message)) echo $success_message; ?></div>
<?php } ?>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<tr>
<td>User Name</td>
<td><input type="text" class="demoInputBox allinsc" name="userName" value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>"></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" class="demoInputBox allinsc" name="firstName" value="<?php if(isset($_POST['firstName'])) echo $_POST['firstName']; ?>"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" class="demoInputBox allinsc" name="lastName" value="<?php if(isset($_POST['lastName'])) echo $_POST['lastName']; ?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" class="demoInputBox allinsc" name="password" value=""></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="password" class="demoInputBox allinsc" name="confirm_password" value=""></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" class="demoInputBox allinsc" name="userEmail" value="<?php if(isset($_POST['userEmail'])) echo $_POST['userEmail']; ?>"></td>
</tr>
<tr>
<td>Date Of birth</td>
<td><input type="date" value="<?php print(date("YYYY-MM-DD"))?>" class="demoInputBox" name="dob" value="<?php if(isset($_POST['dob'])) echo $_POST['dob']; ?>"></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gender" value="Male" <?php if(isset($_POST['gender']) && $_POST['gender']=="Male") { ?>checked<?php } ?>> Male
<input type="radio" name="gender" value="Female" <?php if(isset($_POST['gender']) && $_POST['gender']=="Female") { ?>checked<?php } ?>> Female
<input type="radio" name="gender" value="not specified" <?php if(isset($_POST['gender']) && $_POST['gender']=="not specified") { ?>checked<?php } ?>> not specified
</td>
</tr>
<tr>
<td colspan=2>
<input type="checkbox" name="terms"> I accept Terms and Conditions <input type="submit" name="register-user" value="Register" class="btnRegister"></td>
</tr>
</table>
</form>
<div class="header1"></div>
<div class="hdetail1"></div>
<h class="etegotxt1">Etego</h>
<img src="Etego_Logo.png" alt="Etego logo" width="50" height="50" class="logo1">
</body></html>
There are a number of issues here:
Where you are trying to prepare a statement you are using $db->database->prepare() and if you look at your class the propery database it is a String containing the string members i.e. public $database = "members"; Which explains the error that is being reported
You also appear to have got the mysqli_ API and the PDO API confused and are using some PDO API functions, that will never work they are totally different beasts.
So also change this
/* Email already exists */
/*line 63*/
$db = new DBController;
$db->database->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
} else {
$error_message = "Email already exists";
}
To
/* Email already exists */
/*line 63*/
$db = new DBController;
$stmt = $db->conn->prepare("SELECT * FROM members WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0) {
$error_message = "Email already exists";
}
and you will be using the connection object to prepare the query and all mysqli_ API functions, methods and properties.
UPDATE: Still getting dup accounts created
Your dup account check is in the wrong place in my opinion and should be moved into the index2.php.
Or after this line add a test against $error_message because you are forgetting to test if the Dup email check produced an error.
if(!isset($error_message)) {
require_once("dbcontroller.php");
if ( !isset($error_message) ) {
My strong suggestion would be to do the Dup Email check in index2 and remove it from dbconnect.php as it does not really belong in dbconnect.php as that would be run unnecessarily everytime you want to connect to a database in any script!
The thing is your $database variable is a string that does not have prepare() function. Instead you might want to use the $conn variable that is holding a valid database connection.
To do that, change
$db->database->prepare("SELECT * FROM members WHERE email = ?");
to
$stmt = $db->conn->prepare("SELECT * FROM members WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
Here is the PHP official documentation.
Related
I am new to PHP. I have some doubts regarding PHP constructor. I have used 2 classes. One class contains constructor, Another class has insertion function. So I want to use the variable declared under constructor in order to write the insert query using mysqli. But I don't know how to access it. Can anyone pls help me with this one.
OOPDB.php
<?php
class Connection
{
//public $conn;
public function __construct()
{
$conn=mysqli_connect("localhost","root","Hatheem06","Emp");
if(!$conn)
{
echo "DB not connected";
}
else
{
echo "DB connected Successfully"."<br>";
}
}
?>
FormDB.php
<?php
include ("OOPDB.php");
$obj=new Connection();
class User
{
public function insertion($name,$Uname,$Pswrd,$Age,$Email)
{
/*$sql=$conn->query("INSERT INTO Employee(Name,Username,Password,Age,Email)VALUES('$name','$Uname','$Pswrd','$Age','$Email')");
return $sql;*/
$ret=mysqli_query($conn,"insert into Employee(Name,Username,Password,Age,Email) values('$name','$Uname','$Pswrd','$Age','Email')");
return $ret;
}
}
$Object=new User();
if (isset($_POST['submit']))
{
$name=$_POST['Name'];
$Uname=$_POST['UName'];
$Pswrd=$_POST['pswd'];
$Age=$_POST['Age'];
$Email=$_POST['Email'];
$result=$Object->insertion($name,$Uname,$Pswrd,$Age,$Email);
if($result)
{
echo "Registration Successful";
}
else
{
echo "Not registered";
}
}
?>
<html>
<head><h1 align="center">Employee Details</h1>
<title> Employee </title>
<link rel="stylesheet" type="text/css" href="Style.css">
</head>
<body>
<div class="dtabb">
<form name="name" method="POST">
<table class="Etab">
<tr><td>Enter Your Name</td>
<td><input type="text" name="Name" ></td>
</tr>
<tr>
<td>Enter User Name</td>
<td><input type="text" name="UName" ></td>
</tr>
<tr>
<td>Enter password</td>
<td><input type="password" name="pswd"></td>
</tr>
<tr>
<td>Enter Your Age</td>
<td><input type="text" name="Age" ></td>
</tr>
<tr>
<td>Enter Mail ID of the Employee</td>
<td><input type="text" name="Email" ></td>
</tr>
<tr>
<td colspan="2"><center><input type="submit" name="submit" value="submit"/></center>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
I would suggest a static method in the Connection class that returns the connection handle. And thats all that need to be in that class
The in classes that need to connect call the getCOnn() method and store the connection returned as a property of themselves.
You also shoudl start using parameterised and bound queries, to protect yourself from SQL Injection.
OOPDB.php
<?php
class Connection
{
private $conn = NULL;
public static function getConn {
if (self::conn !== NULL) {
return self::conn;
}
$conn=mysqli_connect("localhost","root","Hatheem06","Emp");
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
} else {
self::conn = $conn;
return $conn;
}
}
}
?>
FormDB.php
<?php
include ("OOPDB.php");
class User
{
private $conn;
public function __construct() {
$this->conn = Connection::getConn();
}
public function insertion($name,$Uname,$Pswrd,$Age,$Email) {
$sql = "insert into Employee
(Name,Username,Password,Age,Email)
values(?,?,?,?,?)");
$stmt = $this->conn->prepare($sql);
if ( ! $stmt ) {
echo $stmt->error;
return false;
}
$stmt->bind_param('sssis', $name,
$Uname,
$Pswrd,
$Age,
$Email
);
$result = $stmt->execute();
if ( ! $result ) {
echo $stmt->error;
return false;
}
return true;
}
}
$Object=new User();
if (isset($_POST['submit'])) {
$name=$_POST['Name'];
$Uname=$_POST['UName'];
$Pswrd=$_POST['pswd'];
$Age=$_POST['Age'];
$Email=$_POST['Email'];
$result=$Object->insertion($name,$Uname,$Pswrd,$Age,$Email);
if($result) {
echo "Registration Successful";
} else {
echo "Not registered";
}
}
?>
I am trying to make a writing board and need to save ID value in the DB when the writer done its saving.
But my db shows only '0' member_idx and it looks my id session maintating is now working.
I attach related code of mine, but please let me know if you need more codes which I've missed.
_this is my work_tree under htdocs of apache2
enter image description here
this is login_check.php
<?php
session_start();
include_once ('../config.php');
$mysqli = new mysqli($DB['host'], $DB['id'], $DB['pw'], $DB['db']);
if (mysqli_connect_error()) {
exit('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
extract($_POST);
$q = "SELECT * FROM ap_member WHERE id='$user_id'";
$result = $mysqli->query($q);
if($result->num_rows==1) {
$encrypted_pass = sha1($user_pass);
$row = $result->fetch_array(MYSQLI_ASSOC);
if( $row['pw'] == $encrypted_pass ) {
$_SESSION['member_idx'] = $row['member_idx'];
header('Location: '.$url['root'].'login_done.php');
}
else {
echo 'wrong password';
}
}
else {
echo 'ID does not exist or invalid approach. Try again.';
}
if( $row['pw'] == $encrypted_pass ) {
$_SESSION['is_logged'] = 'YES';
$_SESSION['user_id'] = $user_id;
$_SESSION['member_idx'] = $row['member_idx'];
header('Location: '.$url['root'].'login_done.php');
exit();
}
else {
$_SESSION['is_logged'] = 'NO';
$_SESSION['user_id'] = '';
header('Location: '.$url['root'].'login_done.php');
exit();
}
?>
_this is write.php
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/preset.php';
include $_SERVER['DOCUMENT_ROOT'].'/header.php';
?>
Write a Commment for anything please <br />
<form name ="write_form" method = "POST" action = "./write_check.php">
<input type="hidden" name="member_idx" value="<?php echo $_SESSION['member_idx'] ?>">
<table>
<tr>
<td>
Title
</td>
<td>
<input type ="text" name = "subject" size ="90">
</td>
</tr>
<tr>
<td>
Content
</td>
<td>
<textarea name="content" cols="100" rows="10"></textarea>
</td>
</tr>
</table>
<div>
<input type = "submit" value = "저장">
</div>
</form>
<?php
include $_SERVER['DOCUMENT_ROOT'].'/footer.php';
?>
_ and finally this is my DB what it looks like now
_+ here's my ap_bbs
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/preset.php';
?>
<?php
$reg_date = time();
$member_idx = $_SESSION['member_idx'];
$q = "INSERT INTO ap_bbs (member_idx, subject,content,reg_date) VALUES('$member_idx', '$subject', '$content', '$reg_date')";
$result = $mysqli->query($q);
if ($result==false) {
$_SESSION['writing_status'] = 'NO';
}
else {
$_SESSION['writing_status'] = 'YES';
}
$mysqli->close();
header('Location: '.$url['root'].'bbs/write_done.php');
exit();
?>
I having 2 problem in my programming.
1)cant update password in mysql db.
change_password.php
<?php
session_start();
require_once 'class.user.php';
$user_home = new USER();
?>
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>(Type a title for your page here)</title>
</head>
<body>
<?Php
///////Collect the form data /////
if(isset($_POST['btn-signup']))
{
$password=$_POST['password'];
$password2=$_POST['password2'];
$old_password=$_POST['old_password'];
/////////////////////////
$stmt = $user_home->runQuery("SELECT * FROM registered_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['password']<>md5($old_password)){
echo"Your old password is not matching as per our record.<BR>";
echo"no same pass";
}
if ( $password <> $password2 ){
$msg=$msg."Both passwords are not matching<BR>";
echo "new pass not same";
$password=md5($password);
$stmt = $this->conn->prepare("UPDATE registered_users SET password=:password where email:email");
$stmt->bindparam(":password",$password);
if($stmt->execute()){
echo "<font face='Verdana' size='2' ><center>Thanks <br> Your password changed successfully. Please keep changing your password for better security</font></center>";
}else{echo "<center>Sorry <br> Failed to change password Contact Site Admin</font></center>";
} // end of if else if updation of password is successful
} // end of if else todo
}
?>
</body>
<form method="post">
<input type="password" name="old_password" placeholder="old pass" />
<input type="password" name="password" placeholder="opassword" />
<input type="password" name="password2" placeholder="password2" />
<button class="btn btn-large btn-primary" type="submit" name="btn-signup">Sign Up</button>
</form>
</html>
output
Your old password is not matching as per our record.
no same pass
old pass <Text fill>
password <Text fill>
password2 <Text fill>
Sign Up <button>
2)how to insert confirm password fill in register page.
user will enter same password again can check it is same
SignUP.php
<?php
session_start();
require_once 'class.user.php';
$reg_user = new USER();
if($reg_user->is_logged_in()!="")
{
$reg_user->redirect('index.php');
}
if(isset($_POST['btn-signup']))
{
$salutation = $_POST['salutation'];
$fullName = $_POST['fullName'];
$nric = $_POST['nric'];
$gender = $_POST['gender'];
$dateOfBirth = $_POST['dateOfBirth'];
$mobileNumber = $_POST['mobileNumber'];
$email = $_POST['email'];
$password = $_POST['password'];
$address = $_POST['address'];
$postalCode = $_POST['postalCode'];
$serialNumber = md5(uniqid(rand()));
$stmt = $reg_user->runQuery("SELECT * FROM registered_users WHERE email=:email_id");
$stmt->execute(array(":email_id"=>$email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
$msg = "
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Sorry !</strong> email allready exists , Please Try another one
</div>
";
}
else
{
if($reg_user->register($salutation,$fullName,$nric,$gender,$dateOfBirth,$mobileNumber,$email,$password,$address,$postalCode,$serialNumber))
{
$id = $reg_user->lasdID();
$key = base64_encode($id);
$id = $key;
$message = "
Dear $salutation $fullName,
<br /><br />
Thank You for registering with us!<br/>
To complete your registration please , just click following link<br/>
<br /><br />
<a href='http://localhost:8080/xampp/bicycleTheft/test5/php/verify.php?id=$id&serialNumber=$serialNumber'>Click HERE to Activate :)</a>
<br /><br />
Thanks,<br/>
<br />
Site Admin";
$subject = "Confirm Registration";
$reg_user->send_mail($email,$message,$subject);
$msg = "
<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Success!</strong> We've sent an email to $email.
Please click on the confirmation link in the email to create your account.
</div>
";
}
else
{
echo "sorry , query could no execute. Pleae go to nearest NPC to register.";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Signup</title>
<!-- Bootstrap CSS -->
<link href="../css/bootstrap.min.css" rel="stylesheet">
<link href="../css/bootstrap-theme.min.css" rel="stylesheet">
<link rel="stylesheet" href="../css/NewFile.css" type="text/css">
</head>
<body>
<script src="../js/jquery-1.12.3.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<?php include 'navBar.php'; ?>
<?php if(isset($msg)) echo $msg; ?>
<div class="padding">
<form class="form-signin" method="post">
<h2 class="form-signin-heading">Sign Up</h2><hr />
<table>
<tr>
<td>Salutation</td>
<td><select name="salutation">
<option value="Dr">Dr</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Madam">Madam</option>
</select>
</td>
</tr>
<tr>
<td>Full Name (as in NRIC):</td>
<td><input type="text" class="input-block-level" placeholder="Full Name" name="fullName" required /></td>
</tr>
<tr>
<td>NRIC:</td>
<td><input type="text" class="input-block-level" placeholder="S1234567A" name="nric" required /></td>
</tr>
<tr>
<td>Gender:</td>
<td><input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female</td>
</tr>
<tr>
<td>Date Of Birth:</td>
<td><input type="date" class="input-block-level" name="dateOfBirth" required /></td>
</tr>
<tr>
<td>Mobile Nume:</td>
<td><input type="text" class="input-block-level" placeholder="91234567" name="mobileNumber" required /></td>
</tr>
<tr>
<td>Email Address:</td>
<td><input type="email" class="input-block-level" placeholder="ABC#example.com" name="email" required /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" class="input-block-level" placeholder="password" name="password" required /></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" class="input-block-level" placeholder="address" name="address" required /></td>
</tr>
<tr>
<td>Postal Code:</td>
<td><input type="text" class="input-block-level" placeholder="postalcode" name="postalCode" required /></td>
</tr>
</table>
<button class="btn btn-large btn-primary" type="submit" name="btn-signup">Sign Up</button>
</form>
</div>
</body>
</html>
class.user.php
<?php
require_once 'dbconfig.php';
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function lasdID()
{
$stmt = $this->conn->lastInsertId();
return $stmt;
}
public function register($salutation,$fullName,$nric,$gender,$dateOfBirth,$mobileNumber,$email,$password,$address,$postalCode,$serialNumber)
{
try
{
$password = md5($password);
$stmt = $this->conn->prepare("INSERT INTO registered_users(salutation,fullName,nric,gender,dateOfBirth,mobileNumber,email,password,address,postalCode,serialNumber)
VALUES(:salutation,:fullName,:nric,:gender,:dateOfBirth,:mobileNumber,:email,:password,:address,:postalCode,:serialNumber)");
$stmt->bindparam(":salutation",$salutation);
$stmt->bindparam(":fullName",$fullName);
$stmt->bindparam(":nric",$nric);
$stmt->bindparam(":gender",$gender);
$stmt->bindparam(":dateOfBirth",$dateOfBirth);
$stmt->bindparam(":mobileNumber",$mobileNumber);
$stmt->bindparam(":email",$email);
$stmt->bindparam(":password",$password);
$stmt->bindparam(":address",$address);
$stmt->bindparam(":postalCode",$postalCode);
$stmt->bindparam(":serialNumber",$serialNumber);
$stmt->execute();
return $stmt;
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
public function registerBike($userID,$typeOfBike,$brand,$model,$colour,$remarks,$serialNumber,$final_file,$folder)
{
try
{
$stmt = $this->conn->prepare("INSERT INTO bike_tbl (userID,typeOfBike,brand,model,colour,remarks,serialNumber,file,location)
VALUES(:userID,:typeOfBike,:brand,:model,:colour,:remarks,:serialNumber,:file,:location)");
$stmt->bindparam(":userID",$userID);
$stmt->bindparam(":typeOfBike",$typeOfBike);
//$stmt->bindparam(":otherBike",$otherBike);
$stmt->bindparam(":brand",$brand);
$stmt->bindparam(":model",$model);
$stmt->bindparam(":colour",$colour);
//$stmt->bindparam(":usedBike",$usedBike);
$stmt->bindparam(":remarks",$remarks);
$stmt->bindparam(":serialNumber",$serialNumber);
$stmt->bindparam(":file",$final_file);
$stmt->bindparam(":location",$folder);
$stmt->execute();
return $stmt;
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
public function updateUser($fullName,$mobileNumber,$password,$address,$postalCode,$email)
{
try
{
$password = md5($password);
$stmt = $this->conn->prepare("UPDATE registered_users SET fullName=:fullName,mobileNumber=:mobileNumber,password=:password,address=:address,postalCode=:postalCode WHERE email=:email");
// $stmt->execute(array(":email"=>$email));
// $userRow=$stmt->fetch(PDO::FETCH_ASSOC);
$stmt->bindparam(":email",$email);
$stmt->bindparam(":fullName",$fullName);
$stmt->bindparam(":mobileNumber",$mobileNumber);
$stmt->bindparam(":password",$password);
$stmt->bindparam(":address",$address);
$stmt->bindparam(":postalCode",$postalCode);
$stmt->execute();
return $stmt;
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
public function login($email,$password)
{
try
{
$stmt = $this->conn->prepare("SELECT * FROM registered_users WHERE email=:email_id");
$stmt->execute(array(":email_id"=>$email));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if($userRow['userStatus']=="Y")
{
if($userRow['password']==md5($password))
{
$_SESSION['userSession'] = $userRow['userID'];
return true;
}
else
{
header("Location: index.php?error1");
exit;
}
}
else
{
header("Location: index.php?inactive");
exit;
}
}
else
{
header("Location: index.php?error2");
exit;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
public function chgpass($currentPassword,$newPassword)
{
try
{
$stmt = $this->conn->prepare("SELECT * FROM registered_users WHERE email=:email_id");
$stmt->execute(array(":email_id"=>$email));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if($userRow['userStatus']=="Y")
{
if($userRow['password']==md5($currentPassword))
{
$_SESSION['userSession'] = $userRow['userID'];
$stmt = $this->conn->prepare("UPDATE registered_users SET password=:newPassword WHERE email=:email");
$stmt->bindparam(":newPassword",$newPassword);
return true;
}
else
{
header("Location: index.php?error1");
exit;
}
}
else
{
header("Location: index.php?inactive");
exit;
}
}
else
{
header("Location: index.php?error2");
exit;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
public function is_logged_in()
{
if(isset($_SESSION['userSession']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_destroy();
$_SESSION['userSession'] = false;
}
function send_mail($email,$message,$subject)
{
require_once('../mailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->AddAddress($email);
$mail->Username="ABTMP16#gmail.com";
$mail->Password="antibicycletheft16";
$mail->SetFrom('ABTMP16#gmail.com','Muahammed Ashik');
$mail->AddReplyTo("ABTMP16#gmail.com","Reply");
$mail->Subject = $subject;
$mail->MsgHTML($message);
$mail->Send();
}
}
?>
You are not binding second parameter :email.
Corrected Answer:
$stmt = $this->conn->prepare("UPDATE registered_users SET password=:password where email:email");
$stmt->bindparam(":password",$password);
$stmt->bindparam(":email",$email); // This line was missing.
I'm trying to write a code that takes two input values( username and password) and compare them with values in a table (named as user) in the database. Now, if the value inserted for the username is "admin" and also the password is "admin". I want to direct the admin to his page, and if the user has inserted his info, I want to direct him to his page also. My code below looks correct but I'm getting no response. How can this be fixed?
I wrote this code for html:
<form name="userLogin" action="LoginCode.php" method="POST" >
<h3>Login</h3>
<table width="450px">
<tr>
<td valign="top">
<label for="first_name">Your Name *</label>
</td>
<td valign="top">
<input type="text" name="user_username" maxlength="50" size="30" required>
</td>
</tr>
<tr>
<td valign="top">
<label for="last_name">Password *</label>
</td>
<td valign="top">
<input type="password" name="user_password" maxlength="50" size="30" required>
</td>
<tr>
<td></td>
<td><input type="submit" name="login" value="Login" required>
</td>
</tr>
</table>
</form>
And this is my LoginCode.php
<?php
include ("../Connections/map_connection.php");
if (isset($_POST["login"])) {
$user_username = $_POST["user_username"];
$user_password = $_POST["user_password"];
/* $user_email=$_POST["user_email"]; */
if ($username = 'admin' and $user_password = 'admin') {
$data = mysql_fetch_array($result);
session_start();
$_SESSION['name'] = $data['user_username'];
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + 400;
header("location: ..Admin/AdminIndex.php");
} else {
$sql = ("select * from user where user_username='$user_username' and user_password= '$user_password' ");
$result = mysql_query($sql);
if (!$result) {
echo "Error" . mysql_error();
} else {
$row = mysql_num_rows($result);
if ($row == 0) {
echo 'Invalid username or password';
} else {
$data = mysql_fetch_array($result);
session_start();
$_SESSION['name'] = $data['user_username'];
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + 400;
header("location: UserIndex.php");
}
}
}
}
?>
Check your if condition,
if ($username = 'admin' and $user_password = 'admin')
Here you are using single '=' i.e assignment operation instead of comparison i.e '=='.
Try this :
if ($username == 'admin' && $user_password == 'admin')
:::::::::::::::::::::::UPDATE:::::::::::::::::::::::::
What does this mean?
if ($username == 'admin' && $user_password == 'admin')
{
$data = mysql_fetch_array($result);
....
}
My point is without mysql_query() you are using mysql_fetch_assoc().
I fixed it !!
<?php
include ("../Connections/map_connection.php");
if (isset($_POST["login"])) {
$user_username= $_POST["user_username"];
$user_password= $_POST["user_password"];
if($user_username=='admin' && $user_password){
$sql= ("select * from admin where admin_username='$user_username' and admin_password= '$user_password' ");
$result = mysql_query($sql);
if(!$result){
echo "Error".mysql_error();
}
else
{
$row= mysql_num_rows($result);
if($row==0) {
echo 'Invalid username or password';
}
else
{
$data= mysql_fetch_array($result);
session_start();
$_SESSION['name'] = $data['admin_username'];
$_SESSION['start']=time();
$_SESSION['expire']= $_SESSION['start'] + 400;
header("location: ../Admin/AdminIndex.php");
}
}
}
else{
$sql= ("select * from user where user_username='$user_username' and user_password= '$user_password' ");
$result = mysql_query($sql);
if(!$result){
echo "Error".mysql_error();
}
else
{
$row= mysql_num_rows($result);
if($row==0) {
echo 'Invalid username or password';
}
else
{
$data= mysql_fetch_array($result);
session_start();
$_SESSION['name'] = $data['user_username'];
$_SESSION['start']=time();
$_SESSION['expire']= $_SESSION['start'] + 400;
header("location: UserIndex.php");
}
}
}
}
?>
So im trying to have a user update their profile from update.php and then display it in userprofile.php but I am getting the error :"Cannot update: Duplicate entry 'username' for key 1". Ive tried to find a solution but im pretty stuck. Any help would be appreciated.
Here is update.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>User Profile Update</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<?php
session_start();
if(!isset($_SESSION['logged']) || $_SESSION['logged'] = TRUE)
{
$userError = "Error! Invalid Username.";
$passError = "Error! Invalid Password.";
$emailError = "Error! Invalid Email.";
$conError = "Error! Passwords do not match.";
$errorCheck = false;
$regex = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}#)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';
if (isset($_POST['update']))
{
if(empty($_POST["firstName"])){
echo $userError;
$errorCheck = True;
}
elseif(empty($_POST["lastName"])){
echo $passError;
$errorCheck = True;
}
elseif(empty($_POST["userName"])){
echo $userError;
$errorCheck = True;
}
elseif(empty($_POST["pass"])){
echo $passError;
$errorCheck = True;
}
elseif(preg_match($regex, $_POST["email"]) != 1) {
echo $emailError;
$errorCheck = True;
}
elseif($_POST["pass"] != $_POST["pass2"]){
echo $conError;
$errorCheck = True;
}
elseif($_POST["address"] != $_POST["address"]){
echo $conError;
$errorCheck = True;
}
if(isset($_POST['update']) && (!$errorCheck)){
$user="bparis";
$pass="soccerguy998";
$database="bparis";
$passwordSub=$_POST["pass"];
$encrypted_mypassword=md5($passwordSub);
$con=mysql_connect("localhost", $user, $pass)
or die ('Couldnt connect to server');
mysql_select_db($database,$con)
or die('could not connect to db');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$key_id = $_POST["userName"];
$key_id2 = $_POST["email"];
//$location = $_POST['location'];
update($key_id2);
}else
{
userupdate();}
}else
{userupdate();}
}else
{ //if no user is logged in, display error
echo "<h1>Access denied</h1>";
echo "<h3><a href=login.php>Click here to login</a></h3>";
}
?>
<?php
function update($email){
$_SESSION['email'] = $email;
$sQry = "SELECT email FROM members WHERE email = " . (int)$_SESSION['email']; // Int userid
$obQry = mysql_query($sQry) or die(mysql_error()); // Shortcut, bad but usable
if (mysql_num_rows($obQry) == 1)
{
// Single record exists:// EDIT USER_PROFILE
$sReplace = "UPDATE members (username,password,email,firstName,lastName,address) VALUES('$_POST[userName]','$encrypted_mypassword','$_POST[email]','$_POST[firstName]','$_POST[lastName]','$_POST[address]')";
// Remember, I assumed that email is an integer!
}
else
{
$passwordSub=$_POST["pass"];
$encrypted_mypassword=md5($passwordSub);
$sReplace = "INSERT INTO members (username,password,email,firstName,lastName,address) VALUES('$_POST[userName]','$encrypted_mypassword','$_POST[email]','$_POST[firstName]','$_POST[lastName]','$_POST[address]')";
}
$obUpdate = mysql_query($sReplace) or die('Cannot update: ' . mysql_error());
if($obUpdate){
$subject = "Profile updated ";
$message = "You have updated your profile with Belfort Furniture. If not please contact customer service at : 703-406-7600";
$Belfortemail = "akomala.akouete#belfortfurniture.com";
echo "<b>profile updated</b>";mail($email, $subject,$message, "From:" . $Belfortemail);}else{
echo "Try update again";}
}
?>
<?php
function userupdate(){
?>
<table>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<h1>Profile Update</h1>
<hr>
<tr><td>First Name:</td><td>
<input type="text" name="firstName" maxlength="20">
</td></tr>
<tr><td>Last Name:</td><td>
<input type="text" name="lastName" maxlength="20">
</td></tr>
<tr><td>Username:</td><td>
<input type="text" name="userName" maxlength="20">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="pass" maxlength="20">
</td></tr>
<tr><td>Confirm Password:</td><td>
<input type="password" name="pass2" maxlength="20">
</td></tr>
<tr><td>Email:</td><td>
<input type="text" name="email" maxlength="50">
</td></tr>
<tr><td>Address:</td><td>
<input type="text" name="address" maxlength="100">
</td></tr>
<!--<tr>
<td class="right">address 1: </td>
<td><input type="text" name="location" value="" size="60" /></td>
</tr>-->
<tr><th colspan=2><input type="submit" name="update" value="UPDATE"></th></tr>
</form>
</table>
<?php
echo "<br><h3><a href=usersProfile.php>View your profile</a></h3>";
}
?>
</body>
</html>
and here is userprofile.php
<?php
session_start();
# DB INFO #
$user="xxxx";
$pass="xxxxx";
$database="xxxxx";
$con=mysql_connect("localhost", $user, $pass)
or die ('Couldnt connect to server');
mysql_select_db($database,$con)
or die('could not connect to db');
$result = mysql_query("SELECT userName,email,firstName,lastName,address FROM members") or die(mysql_error());
showpUsers($result);
function showpUsers($result)
{
?>
<table border="1">
<tr>
<?php
$headings = array("Usernam","Email","First Name","Last Name","Address");
foreach($headings as $info) {
echo "<th border='1'>" . $info . "</th>";
}
?>
</tr>
<?php
if(count($result)>0){
$list = array("username","email","firstName","lastName","address");
//while($data = mysql_fetch_row($result)){
$data = $result;
echo "<tr border='1'>";
for($i=0;$i<count($data);$i++) {
echo "<td border='1'>" . $data[$i] . "</td>";
}
echo "</tr>";
//}
}else{
echo "<b>Empty users list</b>";
}
?>
</table>
<?php
}
echo "<a href=update.php><button type='button'>USER UPDATE</button> </h1>";
?>
<hr/>
<br/>
<h3>Return Home Page</h3>
There are two situations I can see that might cause this:
You have two or more rows in the database with the same username, and your INSERT statement is being called. Check for this explicitly by only calling this block if the number of rows returned was 0. At the moment you aren't testing for it at all.
Your username is the PRIMARY KEY for the table. In this case you should alter your table so that it has a unique auto_incrementing primary key.
Oh, and rewrite the whole thing to fix the massive SQL injection vulnerabilities. Don't let this code anywhere near a public web site in the state it's in.