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";
}
}
?>
Related
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.
I have the following login form :
<?php
include 'database/db_connect.php';
$link = mysqli_connect($host_name, $user_name, $password, $database);
// check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?><?php
session_start();
include 'database/websrvc.php';
$user = new Websrvc();
if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $websrvc->check_login($emailusername, $password);
if ($login) {
// Registration Success
header("location:main.php");
} else {
// Registration Failed
echo 'Wrong username/email or password';
}
}
?>
<form action="" method="post" name="login">
<table class="table " width="400">
<tr>
<th> <label class="fieldstyle_with_label"> UserName or Email: </label> </th>
<td><input type="text" name="emailusername" required></td>
</tr>
<tr>
<th><label class="fieldstyle_with_label"> Password : </label></th>
<td><input type="password" name="password" required></td>
</tr>
<tr>
<td> </td>
<td><input class="large_button" type="submit" name="submit" value="Login" onclick="return(submitlogin());"></td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</form>
When I try to log in using the folowing script, I get the following Fatal Error :
Fatal error: Call to a member function check_login() on a non-object in /homepages/23/d81301375/htdocs/emarps/login
Below is my class web_srvc.php that is supposed that handles the check_login :
public function check_login($emailusername, $password) {
$link = $this->db_connection();
$password = md5($password);
//checking if the username is available in the table
$result = mysqli_query($link, "SELECT user_id,user_name,role_id,status from users WHERE email='$emailusername' or user_name='$emailusername' and password='$password'");
$user_data = mysqli_fetch_array($result, MYSQLI_BOTH);
$count_row = mysqli_num_rows($result);
if ($count_row == 1) {
$_SESSION['login'] = true; // this login var will use for the session thing
$_SESSION['uid'] = $user_data['uid'];
return true;
} else {
return false;
}
}
$login = $websrvc->check_login($emailusername, $password);
change to
$login = $user->check_login($emailusername, $password);
It's my first time using some OOP in PHP.
I have made this simple login system, but for some reason it doesn't seems to be working.
Whenever I enter some details on the page admin_login.php it again redirects me to admin_login.php without saying anything.
I'm not sure what's wrong.
class.admin.php
<?php
include 'inc/inc.functions.php';
include '..dbconnector.php';
class admin
{
public function logged_in()
{
if(isset($_SESSION['adminLogged'])==1)
{
return true;
}
else
{
return false;
}
} //function
public function login_correct($username,$password)
{
global $conn;
try
{
$statement = $conn->prepare("SELECT * from admins where username = ? and password = ?");
$statement->execute(
array(
$username,
$password));
$row=$statement->rowCount();
if($rows > 0)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//funcion
}
?>
admin_login.php
<?php
{
?>
<table>
<form method="post" action="admin_process.php?process=login">
<tr>
<td>Username : </td>
<td><input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td>Password : </td>
<td><input type="password" name="password" id="password" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Login"></td>
</tr>
</form>
</table>
<?php
}
?>
admin_process.php
<?php
session_start();
include 'class/class.admin.php';
include 'dbconnector.php';
$admin = new admin();
if(isset($_REQUEST['process']))
{
switch($_REQUEST['process'])
{
case 'login':
$username = $_POST['username'];
$password = $_POST['password'];
if($admin->login_correct($username, $password))
{
header('refresh:2;URL=admin_home.php');
$_SESSION['adminLogged']=1;
$_SESSION['adminUsername']=$username;
}
else
{
echo "Wrong username or password";
}
break;
default:
header('Location:admin_home.php');
}
}
else
{
header('Location:admin_home.php');
}
?>
All suggestions are welcome.
Change the $_REQUEST['process'] to $_REQUEST['submit'] and then try.
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.
I do have some code in OOP in PHP that's supposed to login/register a user, and a register function works great, but the login function doesn't work and I can't login. And I also have notices that in the array $_SESSION I have undefined indexes "login", "password".
Here is the main page:
<?php
require_once "libs/user_class.php";
$user = User::getObject();
$auth = $user->isAuth();
if(isset($_POST["reg"])){
$login = $_POST["login"];
$password = $_POST["password"];
$reg_success = $user->regUser($login,$password);
}
elseif (isset($_POST["auth"])){
$login = $_POST["login"];
$password = $_POST["password"];
$auth_success = $user->login($login,$password);
if($auth_success){
header("Location:index.php");
exit;
}
}
?>
<html>
<head>
<title>REGISTER</title>
</head>
<body>
<?php
if($auth){
echo "Welcome".$_SESSION["login"];
}
else{
echo '<h2>REGISTRATION</h2>
<form action="index.php" method = "post" name="reg">
<table>
<tr>
<td>Log in</td>
<td>
<input type="text" name = "login" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" name = "password" />
</td>
</tr>
<tr>
<td colspan = "2">
<input type="submit" name="reg" value = "register" />
</td>
</tr>
</table>
</form>
<h2>LOGIN</h2>
<form action="index.php" method = "post" name="auth">
<table>
<tr>
<td>Log in</td>
<td>
<input type="text" name = "login" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" name = "password" />
</td>
</tr>
<tr>
<td colspan = "2">
<input type="submit" name="auth" value = "authorize" />
</td>
</tr>
</table>
</form>';
}
?>
</body>
</html>
And the user_class.php:
<?php
class User{
private $db;
private static $user = null;
private function __construct(){
$this->db = new mysqli("localhost", "root", "root", "temp");
$this->db->query("SET NAMES 'utf8'");
}
public static function getObject(){
if(self::$user === null) self::$user = new User();
return self::$user;
}
public function regUser($login, $password){
if($login == "")return false;
if($password == "")return false;
$password = md5($password);
return $this->db->query("INSERT INTO `users` (`login`, `password`) VALUES ('$login','$password')");
}
private function checkUser($login, $password){
$result_set = $this->db->query("SELECT `password` FROM `users` WHERE `login` = '$login'");
$user = $result_set->fetch_assoc();
$result_set->close();
if(!$user) return false;
return $user["password"] === $password;
}
public function isAuth(){
session_start();
$login = $_SESSION["login"];
$password = $_SESSION["password"];
return $this->checkUser($login,$password);
}
public function login($login, $password){
if($this->checkUser($login, $password)){
session_start();
$_SESSION["login"] = $login;
$_SESSION["password"] = $password;
return true;
}
else return false;
}
public function __destruct(){
if ($this->db) $this->db->close();
}
}
?>
In your database, you are storing the password field with md5 encryption. So, while checking username and password in your login and checkuser function, you nee to check password as md5($password).
Also, I wonder why you have kept the form name and submit button name same.