Regarding write_board and saving member_idx in the DB - php

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();
?>

Related

Fatal error: Call to a member function prepare() on string

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.

Upload file in a form containing multiple textfields using PHP

I'm trying to figure out how to upload a file into the database where that form contains multiple textfields. I uploaded a BLOB field into the database. So as I try to search the field using the ID number, it will retrieve me the values associated with it. Which works fine, so I added the function of being able to upload a file into that specific id number. I get all sorts of errors and I would like to have an assistance with it. Anyone care to help out? Here are the codes:
<?php
$host = "localhost";
$user = "root";
$password ="";
$database = "ntmadb";
$id = "";
$firstname = "";
$lastname = "";
$username = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['firstname'];
$posts[2] = $_POST['lastname'];
$posts[3] = $_POST['username'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM members WHERE id = $data[0]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$username = $row['username'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `members` SET `firstname`='$data[1]',`lastname`='$data[2]',`username`='$data[3]' WHERE `id` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
}
<!--UPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOAD -->
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'ntmadb');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
// Create the SQL query
$query = "
INSERT INTO `members` (
`data`
)
VALUES (
'{$data}' NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
?>
and here is the html file:
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="index4.php" method="post" enctype="multipart/form-data" >
<input type="number" name="id" placeholder="Id" value="<?php echo $id;?>"><br><br>
<input type="text" name="firstname" placeholder="First Name" value="<?php echo $firstname;?>"><br><br>
<input type="text" name="lastname" placeholder="Last Name" value="<?php echo $lastname;?>"><br><br>
<input type="text" name="username" placeholder="User Name" value="<?php echo $username;?>"><br><br>
<div>
<p>
<!-- Input For Edit Values -->
<input type="submit" name="update" value="Update">
<!-- Input For Find Values With The given ID -->
<input type="submit" name="search" value="Find">
</p>
<p>
<input type="file" name="uploaded_file">
<br>
<input type="submit" value="Upload file">
</p>
</div>
</form>
</body>
</html>
Thanks to anyone who can provide me with help. :)

How to write one login form for both the admin and the user

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");
}
}
}
}
?>

PHP Session/Login does not function

Community
I have to programm a small challenge. For that I need a login-system but it does not function.
I hope you can help me with that information.
First I will show you my login page (login.php):
<?php
$host = "localhost";
$user = "root";
$passw = "";
$dbase = "la4s";
$db = mysqli_connect($host, $user, $passw, $dbase);
if(isset($_POST['submit'])) {
$username = $_POST['loginname'];
$password = $_POST['pass'];
$getPassword = mysqli_query($db, "SELECT pw FROM login WHERE username = '".$username."';");
if(mysqli_num_rows($getPassword) == 1) {
while($array = mysqli_fetch_array($getPassword)) {
$passwordFromDB = $array['pw'];
}
$saltPassword = explode("!", $passwordFromDB);
$passwordPeppered = "sd45SFSDF".$password."82hb+22f2!f";
$passwordSaltedAndPeppered = $saltPassword[0].$passwordPeppered;
$passwordMultihash = md5(md5(md5(sha1(sha1(md5(sha1(md5(md5(sha1(sha1(sha1(md5($passwordSaltedAndPeppered)))))))))))));
$passwordFinal = $saltPassword[0].'!'.$passwordMultihash;
$check = mysqli_query($db, "SELECT * FROM login WHERE username = '".$username."' and pw ='".$passwordFinal."';");
if(mysqli_num_rows($check) == 1) {
$getType = mysqli_query($db, "SELECT type FROM login WHERE username = '".$username."';");
$type = mysqli_fetch_assoc($getType);
if($type['type'] == admin) {
session_start();
$_SESSION['admin'] = 1;
header("Location:userconfiguration.php");
}
elseif($type['type'] == "student") {
session_start();
$_SESSION['student'] = 1;
header("Location:home.php");
}
elseif($type['type'] == "teacher") {
session_start();
$_SESSION['teacher'] = 1;
header("Location:teacher.php");
}
else {
echo '<b style="color: red">Invalid Username/Password!</b>';
}
}
else {
echo '<b style="color: red">Invalid Username/Password!</b>';
}
}
else {
echo '<b style="color: red">Invalid Username/Password!</b>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>LA4S - Learning Application For Schools</title>
<link href="./Style/style.css" type="text/css" rel="stylesheet">
</head>
<body>
<div id="div_login">
<img src="./Pictures/logo.png" id="logo" /><br />
<table style="margin:auto;">
<form action="login.php" method="post">
<tr>
<td class="first_row">
Username
</td>
<td>
<input type="text" name="loginname" />
</td>
</tr>
<tr>
<td class="first_row">
Password
</td>
<td>
<input type="password" name="pass" />
</td>
</tr>
<tr>
<td colspan="2" id="button_login">
<input type="submit" name="submit" value="Login" />
</td>
</tr>
</form>
</table>
</div>
</body>
</html>
There is no problem with the password check. That functions right.
In the secure page all things are right, but not the logout function with the session. If I do a logout on the following page and after that I enter the page in the browser, I get this page although I need to login for seeing that. I don't know why. I have learned it so and it always functioned but that time not...
Now the secure page (userconfiguration.php):
<?php
session_start();
if(isset($_GET['logout']) && $_GET['logout'] == 1){
unset($_SESSION['admin']);
}
if(isset($_SESSION['admin'])) {
if($_SESSION['admin'] == 1) {
?>
<!DOCTYPE html>
<html>
<head>
<title>LA4S - Administrator</title>
<link href="./Style/style.css" type="text/css" rel="stylesheet">
</head>
<body>
<script type="text/javascript">
function changeadd() {
document.getElementById("clearuser").style.visibility = "hidden";
document.getElementById("adduser").style.visibility = "visible";
}
function changeclear() {
document.getElementById("adduser").style.visibility = "hidden";
document.getElementById("clearuser").style.visibility = "visible";
}
function error() {
alert("Username cannot be empty!");
}
function error2() {
alert("Password cannot be empty!");
}
function error3() {
alert("This username already exists!");
}
function created() {
alert("User created!");
}
function del() {
alert("User deleted!");
}
</script>
<div>
<img src="./Pictures/logo_small.png" width="100" id="logo" /> <span class="title">Administrator</span>
</div>
<br />
<div class="menu">
<a onclick="changeadd()">Add User</a>
<a onclick="changeclear()">Delete User</a>
<a style="text-decoration: none; color: black" href="login.php?logout=1">Logout</a>
</div>
<br />
<div id="adduser">
<table>
<form action="userconfiguration.php" method="post">
<tr>
<td>
Username
</td>
<td>
<input type="text" name="loginname" />
</td>
</tr>
<tr>
<td>
Password
</td>
<td>
<input type="password" name="pass" />
</td>
</tr>
<tr>
<td>
Type
</td>
<td>
<select name="type" size="1" id="type_select">
<option value="schueler" selected="selected">Schüler</option>
<option value="lehrer">Lehrer</option>
<option value="admin">Admin</option>
</select>
</td>
</tr>
<tr>
<td colspan="2" id="button_login">
<input type="submit" name="submit" value="Add" />
</td>
</tr>
</form>
</table>
</div>
<?php
if(isset($_POST['submit'])) {
$host = "localhost";
$user = "root";
$passw = "";
$dbase = "la4s";
$db = mysqli_connect($host, $user, $passw, $dbase);
if(mysqli_connect_errno()) {
echo mysqli_connect_errno();
die("Error");
}
if($_POST['loginname'] == null) {
echo "<script type=\"text/javascript\">error();</script>";
}
elseif($_POST['pass'] == null) {
echo "<script type=\"text/javascript\">error2();</script>";
}
else {
$username = mysqli_real_escape_string($db,htmlentities($_POST['loginname']));
$pw = mysqli_real_escape_string($db,htmlentities($_POST['pass']));
$passwordPeppered = "sd45SFSDF".$pw."82hb+22f2!f";
$s=str_shuffle("$?!-,.0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
$salt = substr($s, mt_rand(0, 50), 10);
$passwordSaltedAndPeppered = $salt.$passwordPeppered;
$passwordMultihash = md5(md5(md5(sha1(sha1(md5(sha1(md5(md5(sha1(sha1(sha1(md5($passwordSaltedAndPeppered)))))))))))));
$passwordFinal = $salt.'!'.$passwordMultihash;
$type = $_POST['type'];
$checkUsers = mysqli_query($db, "SELECT username FROM login WHERE username = '".$username."';");
if(mysqli_num_rows($checkUsers) == 0) {
mysqli_query($db,"INSERT INTO login (username, pw, type) VALUES ('".$username."', '".$passwordFinal."', '".$type."');");
mysqli_insert_id($db);
echo "<script type=\"text/javascript\">created();</script>";
}
else {
echo "<script type=\"text/javascript\">error3();</script>";
}
}
mysqli_close($db);
}
?>
<div id="clearuser" style="visibility: hidden">
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbase = "la4s";
$db = mysqli_connect($host, $user, $pass, $dbase);
if (mysqli_connect_errno())
{
echo mysqli_connect_errno();
die ("Error");
}
if(isset($_GET['d'])) {
mysqli_query($db, "DELETE FROM login WHERE id=".$_GET['d'].";");
echo "<script type=\"text/javascript\">del();</script>";
}
$getUsers = mysqli_query($db, "SELECT * FROM login");
echo "<table><tr><td><b>Username</b></td><td><b>Löschen</b></td></tr>";
while($ResultArray = mysqli_fetch_array($getUsers)) {
echo "<tr><td>";
echo $ResultArray['username'];
echo "</td><td>";
echo '<a style="color: red" href="userconfiguration.php?d='.$ResultArray["id"].'">X</a>';
echo "</td></tr>";
}
echo "</table>";
mysqli_close($db);
?>
</div>
<?php
}
else {
echo "Not allowed!";
}
}
else {
echo "Not allowed!";
}
?>
</body>
</html>
I hope you can help me. I have looked the whole day for a solution for this problem but I didn't found one. If you need more information, contact me. Thanks
Greez
Tomi
Explanation:
If you var_dump your session after you logged out you will see that you are still 'logged in':
var_dump($_SESSION);
array (size=1)
'admin' => int 1
So we can see the Logout is working incorrectly as it is not clearing the $_SESSION.
If you look at your logout action you are calling the login page:
<a style="text-decoration: none; color: black" href="login.php?logout=1">Logout</a>
So you need to make sure the $_SESSION login is unset in the login.php. As currently it is in the userconfiguration.php:
if(isset($_GET['logout']) && $_GET['logout'] == 1){
unset($_SESSION['admin']);
}
Solution:
Add the following to the top of your login.php:
session_start();
if(isset($_GET['logout']) && $_GET['logout'] == 1){
unset($_SESSION['admin']);
}

"Cannot update: Duplicate entry '*username*' for key 1"

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.

Categories