displaying message when theres duplicate entries not working - php

I have a page where theres a button, when I click the button a Modal shows up, which contains a form for adding a new user.
in the user table, username + email + userid are primary keys. So I need to validate first that they don't exist in the table.
Now inserting works just fine. also when I insert an already existing username/userid/email it doesn't get added. However, the alert doesn't show. so the user won't know why it wasn't added
try
{
if(isset($_POST['submit']))
{
if($_POST['submit'] == 'إضافة'){
$user_name = $_POST['user_name'];
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$role = $_POST['role'];
$userid = $_POST['userid'];
//check to see if username/email/userid already exists
//Check username
$stmt1 = $conn->prepare("SELECT * FROM users WHERE username='$user_name'");
//Check email
$stmt2 = $conn->prepare("SELECT * FROM users WHERE E-mail='$email'");
//Check userid
$stmt3 = $conn->prepare("SELECT * FROM users WHERE id=$userid");
$stmt1->execute();
$stmt2->execute();
$stmt3->execute();
if (mysqli_num_rows($stmt1)>0)
{
$name_error = "username already exists";
die();
}
else if (mysqli_num_rows($stmt2)>0)
{
$name_error = "email already exists";
die();
}
else if (mysqli_num_rows($stmt3)>0)
{
$name_error = "employee id already exists";
die();
}
//if username/email/userid don't exist, proceed with the insert query.
else
{
$stmt = $conn->prepare("INSERT INTO `user` (`id`, `username`, `name`, `E-mail`, `Password`, `Role`, `User_Id`) VALUES (NULL, '$username', '$Name', '$email', '$password', '$role', $userid)");
$stmt->execute();
$lastIntertedId = $conn->lastInsertId();
}
I added the following to the text fields, so the error shows beneath them.
<!-- Add User Modal -->
<div id="addUserModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form method="POST" action="user_managment.php" >
<div class="modal-header">
<h4 class="modal-title">إضافة مستخدم </h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>اسم المستخدم</label>
<input name="user_name" type="text" class="form-control" required>
<?php if(isset($name_error)): ?>
<span><?php echo $name_error;?></span>
<?php endif ?>
</div>
<div class="form-group">
<label>الاسم</label>
<input name="name" type="text" class="form-control" required>
</div>
<div class="form-group">
<label>الرقم الوظيفي</label>
<input name="userid" type="number" class="form-control" required>
<?php if(isset($name_error)): ?>
<span><?php echo $name_error;?></span>
<?php endif ?>
</div>
<div class="form-group">
<label>دور المستخدم </label>
<select name="role" class="form-control" id="sel1">
<option value="admin">مشرف</option>
<option value="employee">مدخل بيانات</option>
</select>
</div>
<div class="form-group">
<label>البريد الالكتروني</label>
<input name="email" type="email" class="form-control" required>
<?php if(isset($name_error)): ?>
<span><?php echo $name_error;?></span>
<?php endif ?>
</div>
<div class="form-group">
<label>الرقم السري</label>
<input name="password" type="password" class="form-control" required>
</div>
</div>
<div class="modal-footer" >
<input name="submit" type="submit" class="btn btn-success" value="إضافة">
<input type="button" class="btn btn-default" data-dismiss="modal" value="إلغاء">
</div>
</form>
</div>
</div>
</div>

Isn't your UserId a generated value in your DB's schema ?
If i understand correctly what you are trying to achieve, you shouldn't be able to know if your user_id already exist since you shouldn't have a user_id at the moment you are trying to execute your form.
Here's how i understand your page:
You have a page, on this page there's a modal to add new user, in this page you verify if there's already an existing user with the same Email | Username | Id, but my issue is that you can't know the user_id of a user that hasn't been created yet, and also you shouldn't validate a duplicate based on an auto-generated value by your DB (imo)
I hope my message is understandable, what i want to say is that you can't verify the existence of something that hasn't been created yet.

Related

How can i get my registration form page to work with php?

please i'm kinda new to website development. i tried to create a registration page to work with my database but my registration form page is not responding to the php coding page.
please i need your assistance. thank
This is my registration.html page
i don't know if the error is from my registration form page
<form action="student.php" name="register" id="register" method="POST" data-aos="fade">
<div class="form-group row">
<div class="col-md-6 mb-3 mb-lg-0">
<input type="text" name="firstname" id="firstname" class="form-control" placeholder="First name" required>
</div>
<div class="col-md-6">
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Last name" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="text" name="studentid" id="studentid" class="form-control" placeholder="Student ID" value="" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="text" name="level" class="form-control" placeholder="Level" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<p class="mb-0">Gender</p>
<input name="gender" type="radio" value="m" required> Male
<input name="gender" type="radio" value="f" required> Female
</div>
</div>
<div class="form-group row">
<div id="date-picker" class="col-md-12 md-form md-outline input-with-post-icon datepicker" inline="true">
<input type="text" name="dob" class="form-control" id="date9" placeholder="DD/MM/YYYY" required>
<i class="fas fa-calendar input-prefix"></i>
</div>
</div>
<script>
$('.datepicker').datepicker({
inline: true;
});
</script>
<div class="form-group row">
<div class="col-md-12">
<input type="email" name="email" class="form-control" placeholder="Email" value="" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="phone" name="phonenumber" id="phonenumber" class="form-control" placeholder="+234 8179 5523 71" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="department" name="department" class="form-control" placeholder="Department" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="password" name="password" value="" id="password" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<input type="password" name="confirmpassword" id="confirmpassword" value="" class="form-control" placeholder="Confirm Password" required>
</div>
</div>
<div class="form-group row">
<div class="col-md-6">
<input type="submit" name="submit" class="btn btn-primary py-3 px-5 btn-block btn-pill" value="SUBMIT">
</div>
</div>
</form>
This is my Php page for the form
or maybe the error is from my php code. please help detect the problem guys. Thanks.
<?php
session_start();
// initializing variables
$studentid = "";
$email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'oneschool');
// REGISTER USER
if (isset($_POST['submit'])) {
// receive all input values from the form
$firstname = mysqli_real_escape_string($db, $_POST['firstname']);
$lastname = mysqli_real_escape_string($db, $_POST['lastname']);
$studentid = mysqli_real_escape_string($db, $_POST['studentid']);
$level = mysqli_real_escape_string($db, $_POST['level']);
$gender = mysqli_real_escape_string($db, $_POST['gender']);
$dob = mysqli_real_escape_string($db, $_POST['dob']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$phonenumber = mysqli_real_escape_string($db, $_POST['phonenumber']);
$department = mysqli_real_escape_string($db, $_POST['department']);
$password_1 = mysqli_real_escape_string($db, $_POST['password']);
$password_2 = mysqli_real_escape_string($db, $_POST['confirmpassword']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($studentid)) { array_push($errors, "Student ID is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM student_registra WHERE studentid='$studentid' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query) or die(mysqli_error($db));
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['studentid'] === $studentid & $user['email'] === $email) {
array_push($errors, "Student Id already taken");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO student_registra (firstname, lastname, studentid, level, gender, dob, email, phonenumber, department, password)
VALUES('$firstname', '$lastname', '$studentid', '$level', '$gender', '$dob', '$email', '$phonenumber', '$department', '$password')";
mysqli_query($db, $query);
$_SESSION['studentid'] = $studentid;
$_SESSION['success'] = "Registration Sucessful";
header('location: index.html');
}
}
i don't know what seems to be the problem, because i run it the first time it worked, but when i shutdown my laptop and turn it on back again after my lunch, it stop working.
Instead of it to read the .php code it's rather displaying the whole .php code and i've checked the code, i can't find what seems to be the problem.
please guys, i'll need your help in fixing this or detecting the problem.
thanks
EDIT, You have a lot of useless codes that make your code so slow, Like $_SESSION['success']; This is not neccessary, Change your index.html to index.php and delete it because it do nothing, You can check session by student id You have two gender Inputs, how comes you assign one of them? This is first mistake
Secondly, Use Prepared Statements to avoid SQLI Attacks
Thirdly How comes you header a html page when you're in php page? change index.html to index.php
And Use this code instead:
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$prepared = "INSERT INTO student_registra (firstname, lastname, studentid, level, gender, dob, email, phonenumber, department, password)
VALUES('$firstname', '$lastname', '$studentid', '$level', '$gender', '$dob', '$email', '$phonenumber', '$department', '$password')";
$query = $prepared;
mysqli_query($db, $query);
$_SESSION['studentid'] = $studentid;
# Change your files index.html To index.php
header('location: index.php');
}

PHP prepare-statement User Change password

This is the html code for the change password page. When I click change password from the user registration table, it bring me here and it works perfectly but when you use the option of the user change password which leads you directly to this place, saving it doesn't work. I believe it's got to deal with the User ID as key since from the table is selected via ID. But when i use setting - user change password, it doesn't do anything after saving password change, it doesn't reflect anything
<div class="col-lg-6">
<div class="col-sm-12">
<br/>
<h3 class="page-title">Change Password</h3>
</div>
<div class="card-box">
<div class="form-group">
<label for="userName">User Name</label>
<input type="text" name="uname" parsley-trigger="change" required placeholder="Enter user name" class="form-control" id="uname" name="uname" value="<?php echo $actordetails->ACT_USERNAME;?>" readonly >
</div>
<div class="form-group">
<label for="pass1">New Password<span style="color:#F00">*</span></label>
<input id="pass1" type="password" placeholder="Password" name="inputpassword" required class="form-control">
</div>
<div class="form-group">
<label for="passWord2">Confirm New Password <span style="color:#F00">*</span></label>
<input data-parsley-equalto="#pass1" type="password" required placeholder="Password" class="form-control" id="password2">
</div>
<div class="form-group text-right m-b-0">
<button class="btn btn-success waves-effect waves-light" type="submit" onclick="document.getElementById('viewpage').value='savepwd';document.getElementById('view').value='';document.getElementById('fdsearch').value='';document.myform.submit()">
Save
</button>
<button class="btn btn-default waves-effect waves-light m-l-5" onclick="document.getElementById('view').value='';document.getElementById('viewpage').value='';document.myform.submit()">
Cancel
</button>
</div>
</div>
</div>
</form >
and this is the controller code to process the information. The encryption uses username and password with salt for your information.. Any help would be appreciated
<?php
$crypt = new cryptCls();
switch(strtolower($viewpage)) {
case "changepwd":
print_r($_POST);
$stmt = $sql->Execute($sql->Prepare("
SELECT ACT_USERNAME,ACT_ID
FROM gm_actors
WHERE ACT_ID=".$sql->Param('a')),array($keys));
print $sql->ErrorMsg();
if($stmt->RecordCount()>0){
$editobj = $stmt->FetchNextObject();
$uname = $actordetails->ACT_USERNAME;
}
break;
case "savepwd":
print_r($_POST);
$duplicatekeeper = $session->get("post_key");
if($action_key != $duplicatekeeper){
$session->set("post_key",$action_key);
if(!empty($inputpassword) && !empty($keys) ) {
$inputpassword = $crypt->loginPassword($uname,$inputpassword);
$stmt = $sql->Execute($sql->Prepare("
UPDATE gm_actors
SET ACT_USERPASSWORD=".$sql->Param('b')."
WHERE ACT_ID=".$sql->Param('d')." "),
array($inputpassword,$actordetails->ACT_ID));
$msg = "Password has been changed successfully.";
$status = "success";
// $activity = ' Agent'.$keys.' password changed .';
// $engine->setEventLog("032",$activity);
}else if($inputpassword!==$confirmpassword){
$msgs="Sorry! Passwords Do not Match.";
$target ='changepwd';
} else {
$msg = "Unsuccessfully: All fields are required.";
$status = "error";
$view ="changepwd";
}
}
break;
}
$stmtusers = $sql->Execute($sql->Prepare("
SELECT ACT_SURNAME,ACT_ID,ACT_OTHERNAMES,
ACT_USERNAME,ACT_STATUS,ACT_EMAIL,ACT_PHONE,
ACT_ACCESS_LEVEL,ACL_NAME
FROM gm_actors
left join gm_actors_level on ACT_ACCESS_LEVEL=ACL_NUMBER
WHERE ACT_ACCESS_LEVEL !='1'
AND ACT_STATUS !='4'
ORDER BY ACT_SURNAME "));
print $sql->ErrorMsg();
include("model/js.php");
include('public/alertmessage/message.php');
?>

I want show message about existing username under username input tag and when show the message other the data doesn't lose in php

I want show message about existing username under username input tag and when show the message other the data doesn't lose. But this codes don't work.
Here is my code for existing username:
<?php
//click register button
if(isset($_POST['register']))
{
//Retrieve the field values from our registration form.
$username = $_POST['username'];
//Now, we need to check if the supplied username already exists.
$sql = "SELECT COUNT(user_username) AS num FROM users WHERE user_username = :username";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
echo "<script>";
echo "$(document).ready(function(){document.getElementById('existing_username').innerHTML = 'existing'})";
echo "</script> ";
//the following code is work but other data like name, password is lost in input element
//echo '<div class="alert alert-danger"> <b>'.$username.'</b> This username already exist!</div>';
} }
?>
And here is my code for input data:
<form action="register.php" method="post">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="username"><b>USERNAME</b></label>
<input class="form-control" type="text" id="username" name="username">
</div>
</div>
</div>
<span class="text-danger" id="existing_username"></span>
<button class="btn btn-primary" type="submit" name="register" value="Register">Register</button>
</form>
when show the message other the data doesn't lose
What data?!
ok,so you should store the error message which is Username exist in a variable,like below :
<?php
//click register button
if(isset($_POST['register']))
{
//Retrieve the field values from our registration form.
$username = $_POST['username'];
//Now, we need to check if the supplied username already exists.
$sql = "SELECT COUNT(user_username) AS num FROM users WHERE user_username = :username";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
echo "<script>";
echo "$(document).ready(function(){document.getElementById('existing_username').innerHTML = 'existing'})";
echo "</script> ";
$error = "<b>".$username."</b> :This username already exist!";
//this code is work but other data is lost
} }
?>
<form action="register.php" method="post">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="username"><b>USERNAME</b></label>
<input class="form-control" type="text" id="username" name="username">
</div>
</div>
</div>
</form>
Check this answers too Embed Php in Html
You need to provide value attribute for your form fields. For example:
<input class="form-control" type="text" id="username" name="username" value="<?php echo $username ?>">
OR
<input class="form-control" type="text" id="name" name="name" value="<?php echo $name ?>">
etc.
Of course you need to define these variables in you code first. If form have been submitted - take them from $_POST. If not - set them as empty values.
Code example with 2 fields:
<?php
$name = null;
$username = null;
//click register button
if (isset($_POST['register'])) {
//Retrieve the field values from our registration form.
$name = $_POST['name'];
$username = $_POST['username'];
//Now, we need to check if the supplied username already exists.
$sql = "SELECT COUNT(user_username) AS num FROM users WHERE user_username = :username";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row['num'] > 0) {
echo "<script>";
echo "$(document).ready(function(){document.getElementById('existing_username').innerHTML = 'existing'})";
echo "</script> ";
$error = "<b>".$username."</b> :This username already exist!";
//this code is work but other data is lost
}
}
?>
<form action="register.php" method="post">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="name"><b>NAME</b></label>
<input class="form-control" type="text" id="name" name="name" value="<?php echo $name ?>">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="username"><b>USERNAME</b></label>
<input class="form-control" type="text" id="username" name="username" value="<?php echo $username ?>">
</div>
</div>
</div>
<span class="text-danger" id="existing_username"></span>
<button class="btn btn-primary" type="submit" name="register" value="Register">Register</button>
</form>

Data is not inserting into phpMyAdmin database PHP MySQL from Bootstrap Modal

Not sure where is a problem.
Really, the thing is that after submitting the page refreshes and it looks like code worked well.
But when I refresh my database there is no new data...
Modal (file path incl/modals.inc.php and is included in index.php file):
<div class="modal fade" id="addPlayer" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add Player </h4>
</div>
<div class="modal-body">
<form action="incl/addplayer.inc.php" method="POST" class="form" role="form">
<div class="row">
<div class="col-xs-6 col-md-6">
<input class="form-control" name="addname" placeholder="First Name (*)" type="text" />
</div>
<div class="col-xs-6 col-md-6">
<input class="form-control" name="addsurname" placeholder="Last Name (*)" type="text" />
</div>
</div><br/>
<div class="row">
<div class="col-xs-6 col-md-6">
<input class="form-control" name="addlvpoints" placeholder="LV points" type="text" />
</div>
<div class="col-xs-6 col-md-6">
<input class="form-control" name="additfpoints" placeholder="ITF points" type="text" />
</div>
</div><br/>
<div class="row">
<div class="col-xs-6 col-md-6 col-md-offset-3">
<input class="form-control" name="addrank" placeholder="Rank" type="text" />
</div>
</div><br/>
<div class="row">
<div class="col-xs-6 col-md-6">
<label for="">
Gender</label>
<br/>
<label class="radio-inline">
<input type="radio" name="addgender" value="M" name="male" />
Male
</label>
<label class="radio-inline">
<input type="radio" name="addgender" value="F" name="female" />
Female
</label>
</div>
</div>
<br/><br/>
(*) - Required
<br/>
<br />
<button class="btn btn-lg btn-default btn-block" type="submit" name="addsubmit">
Add Player
</button>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
Action file (incl/addplayer.inc.php) :
<?php
include '../core.php';
if(isset($_POST['addsubmit'])){
$rank = $_POST['addrank'];
$name = $_POST['addname'];
$surname = $_POST['addsurname'];
$lvpoints = $_POST['addlvpoints'];
$itfpoints = $_POST['additfpoints'];
$gender = $_POST['addgender'];
if(empty($name) || empty($surname) || empty($gender)){
header("Location: ../index.php?error=empty");
exit();
} else {
$sql = "INSERT INTO 'players' ('id', 'rank', 'surname', 'name', 'lvpoints', 'itfpoints', 'gender') VALUES (NULL, '$rank', '$surname', '$name', '$lvpoints', '$itfpoints', '$gender')";
$result = mysqli_query($conn, $sql);
header("Location: ../index.php?addedsuccessfuly");
}
}
?>
When submit the form it goes to
header("Location: ../index.php?addedsuccessfuly");
as excepted
Column structure:
id | rank | surname | name | lvpoints | itfpoints | gender
Thanks in advance!
First try changing:
$result = mysqli_query($conn, $sql);
To:
$result = mysqli_query($sql);
Secondly, remove the insert to ID. If you have set it as "auto increment" in phpmyadmin, the ID will increment automagically. So from:
$sql = "INSERT INTO 'players' ('id', 'rank', 'surname', 'name', 'lvpoints', 'itfpoints', 'gender') VALUES (NULL, '$rank', '$surname', '$name', '$lvpoints', '$itfpoints', '$gender')";
To:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$rank = $_POST["addrank"];
$surname = $_POST["addsurname"];
$name = $_POST["addname"];
$ivp = $_POST["addlvpoints"];
$ift = $_POST["additfpoints"];
$gender = $_POST["addgender"];
$sql = "INSERT INTO players (rank, surname, name, ivpoints, itfpoints, gender)
VALUES ('$rank', '$surname', '$name', '$ivp', '$ift', '$gender')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Now, the code could be a lot more elegant and better, but there are literally tons of articles on the Internet about inserting into databases securly that also explains "do's" and "don't's" in more detail and a lot better - just a Google search away.
There are a lot of answers to this on Stackoverflow too.

Profile page not displaying user profile information or updating [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hope someone can help. I have a profile page that I want to display the logged in users details. So far I have this on the Profile page.
<?php
/* This script pulls the existing name input and displays it when the user logs in. */
session_start();
include("db.php"); ?>
<?php include("includes/header.php") ?>
<?php include("includes/nav.php") ?>
<?php
if(logged_in()) {
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
if (!$_POST['name'] && $_POST['name']=="") $error.="<br />Please enter your name";
if (!$_POST['email'] && $_POST['email']=="") $error.="<br />Please enter your email";
if (!$_POST['DOB'] && $_POST['DOB']=="") $error.="<br />Please enter your date of birth";
if (!$_POST['country'] && $_POST['country']=="") $error.="<br />Please enter your country";
if ($error) {
echo '<div class="alert alert-success alert-dismissable">'.addslashes($error).'</div>';
}
if(isset($_POST['form-control'])) {
move_uploaded_file($_FILES['file']['tmp_name'],"img/".$_FILES['file']['name']);
$query = mysqli_query("UPDATE users SET image = '".$_FILES['file']['name']."'");
}
} else {
redirect("login.php");
}
?>
<Style>
.alert{
display:none;
}
#profileimg {
height: 100px;
width: auto;
}
</Style>
<div class="container">
<h1>Edit Profile</h1>
<hr>
<div class="row">
<!-- left column -->
<div class="col-md-3">
<div class="text-center">
<img src="//placehold.it/100" class="avatar img-circle" alt="avatar" id="profileimg">
<h6>Upload a different photo...</h6>
<input class="form-control" type="file" name="name">
</div>
</div>
<!-- edit form column -->
<div class="col-md-9 personal-info">
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Profile updated.</strong>
</div>
<h3>Personal info</h3>
<form class="form-horizontal" role="form" action="edit_profile.php" method="post">
<div class="form-group">
<label class="col-lg-3 control-label name">name:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['name'];?>" type="text" name="name" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['email'];?>" type="text" name="email" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">DOB:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['DOB'];?>" type="date" name="DOB" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Country</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['country'];?>" type="text" name="country" required>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" value="Save Changes" type="submit">
<span></span>
<input class="btn btn-default" id="updated" value="Cancel" type="reset">
</div>
</div>
</form>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script>
$("#updated").click(function(){
$(".alert").hide().show('medium');
</script>
</body>
</html>
I then have another php file for the updating which is this:
<?php
session_start();
include("db.php");
$name = $_POST['name'];
$email = $_POST['email'];
$DOB = $_POST['DOB'];
$country = $_POST['country'];
$password = md5($salt.$_POST['password']);
$query = "UPDATE users SET name = '".$name."', email = '".$email."', DOB = '".$DOB."', country = '".$country."', password = '".$password."'";
$result = mysqli_query($link,$query);
header('Location: profile.php');
?>
So the short is it doesn't display or update and I am not sure why. I am new to PHP so go easy on me if this is simple, I have searched but can't seem to find the answer.
Thanks in advance.
Im also new to this but normally when I check if a SESSION id is active I use
if(isset($_SESSION['id'])) {
$query = "UPDATE users SET name = '".$name."', email = '".$email."', DOB = '".$DOB."', country = '".$country."', password = '".$password."' WHERE id='".$_SESSION['id']."'";
}
You also need to echo back the indexed rows that you are trying to query to display results
$name = row['username'];
echo $name;
There are lots of errors in your code: You are trying to upload a file in the same page whereas you send the form data to another page. How you handle form validation is also a little overhead. What I did change in the form is: I add name="save" in your submit button and added new hidden input for storing your user profile id. I am not sure what login() function did in your code, better stick to if($id){}.
Try this:
<?php
/* This script pulls the existing name input
and displays it when the user logs in. */
session_start();
include("db.php");
include("includes/header.php");
include("includes/nav.php");
$id = $_SESSION['id'];
if(loginned()) {//you can do if($id){}
$query="SELECT * FROM users WHERE id='$id' LIMIT 1";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
?>
<style>
.alert{
display:none;
}
#profileimg {
height: 100px;
width: auto;
}
</style>
<div class="container">
<h1>Edit Profile</h1>
<hr>
<div class="row">
<!-- left column -->
<!-- edit form column -->
<div class="col-md-9 personal-info">
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert"
aria-hidden="true">×</button>
<strong>Profile updated.</strong>
</div>
<h3>Personal info</h3>
<form class="form-horizontal" role="form"
action="edit_profile.php" method="post">
<div class="form-group">
<label class="col-lg-3 control-label name">name:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['name'];?>"
type="text" name="name" required>
</div>
</div>
<div class="col-md-3">
<div class="text-center">
<img src="//placehold.it/100" class="avatar
img-circle" alt="avatar" id="profileimg">
<h6>Upload a different photo...</h6>
<input class="form-control" type="file" name="name">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['email'];?>"
type="text" name="email" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">DOB:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['DOB'];?>"
type="date" name="DOB" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Country</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['country'];?>"
type="text" name="country" required>
</div>
</div>
<div class="form-group">
<input type="hidden" name="id" value="<?php echo $row['id'];?>">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" name="save"
value="Save Changes" type="submit">
<span></span>
<input class="btn btn-default" id="updated"
value="Cancel" type="reset">
</div>
</div>
</form>
</div>
<?php }else{ redirect("login.php"); } ?>
edit_profile.php First we check whether any post with a name of save is there, We validate the posted data. if validation is successful, we proceed to upload your file and then run your update query.
<?php
session_start();
include("db.php");
if(isset($_POST['save'])){
$id = isset($_POST['id'])? $_POST['id']:'';
$name = isset($_POST['name'])? $_POST['name']:'';
$email = isset($_POST['email'])? $_POST['email']:'';
$dob = isset($_POST['DOB'])? $_POST['DOB']:'';
$pass = isset($_POST['passwrd'])? md5($salt.$_POST['password']):'';
$country = isset($_POST['country'])? $_POST['country']:'';
if(empty($name)){
$error = 'Please enter your name';
}elseif(empty($email)){
$error = 'Please enter your email';
}elseif(empty($dob)){
$error = 'Please enter your date of birth';
}elseif(empty($country)){
$error = 'Please enter your country';
}elseif(empty($pass)){
$error = 'Please enter your password';
}else{
move_uploaded_file($_FILES['file']['tmp_name'],"img/".$_FILES['file']['name']);
$query = mysqli_query("UPDATE users SET image = '".$_FILES['file']['name']."'
WHERE id='$id'");
$query = "UPDATE users SET name = '$name', email = '$email',
DOB = '$DOB', country = '$country', password = '$password'
WHERE id='$id'";
$result = mysqli_query($link,$query);
header('Location: profile.php');
}
}
?>
<?php if(!empty($error)){
echo '<div class="alert alert-success
alert-dismissable">'.addslashes($error).'</div>';
}else{
echo '<div class="alert alert-success">Success</div>';
}
?>
I have added a demo here. At least this will help:

Categories