I have a table that is being displayed on the user screen. When the user clicks on edit, I want him to be able to click the parameters of that specific row and to update a single parameter (e.g., name); then, the other parameters (e.g., email, password, and address) should remain the same.
name email password address action
user user#gmail.com user u.address edit
The code used for the edit link is:
echo"<td class='center'><a class='btn btn-info' href=\"admin_edit_user.php?id=".$row['id']."\"><i class='glyphicon glyphicon-edit icon-white'></i>Edit</a></td>";
Code on admin_edit_user.php page:
<form class="form-horizontal" role="form" action="admin_update_user.php" enctype="multipart/form-data" method="post">
<div class="form-group">
<label class="col-lg-3 control-label">Name</label>
<div class="col-lg-8">
<input class="form-control" name="name" value="" type="text">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email</label>
<div class="col-lg-8">
<input class="form-control" name="email" value="" type="text">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Password</label>
<div class="col-lg-8">
<input class="form-control" name="password" value="" type="text">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Address</label>
<div class="col-lg-8">
<input class="form-control" name="address" value="" type="text">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="submit">
<input class="btn btn-primary" value="Save Changes" type="submit" name="submit">
</div>
</div>
</form>
After this form the user gets redirected to admin_update_user.php page
<?php
$con=mysqli_connect("localhost","root","","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
$query="SELECT * FROM user";
$result= mysqli_query($con, $query) or die(mysqli_error());
while ($row= mysqli_fetch_array($result))
{
$name_data=$row['name'];
$name_email=$row['email'];
$name_password=$row['password'];
$name_address=$row['address'];
}
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$email=$_POST['email'];
$password=$_POST['password'];
$address=$_POST['address'];
if(empty($name))
{
//if the value is empty its going to set it equal to the database value
$name=$name_data;
}
else
$name=$name;
if(empty($email))
{
$email=$name_email;
}
else
$email=$email;
if(empty($password))
{
$password=$name_password;
}
else
$password=$password;
if(empty($address))
{
$address=$name_address;
}
else
$address=$address;
}
//0: demo.name (value given for name)
//demo#gmail.com (value given for email)
//demo (value given forpassword)
//demo
//demo.address (value given for address)
$sql = "UPDATE user SET name='".$name."',email='".$email."',password='".$password."',address='".$address."' WHERE id ='".$id."'";
echo mysqli_errno($con) . ": " . mysqli_error($con) . "\n";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header("Location: admin_user_list.php");
exit;
mysqli_close($con);
?>
I am getting an error in update query. I would be highly obliged if someone could help.
P.S # FortMauris here is the edited part that you wished to see.
$id = $_GET['id'];
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$address = mysqli_real_escape_string($con, $_POST['address']);
$query="SELECT * FROM user";
$result= mysqli_query($con, $query) or die(mysqli_error());
//get the value from database
while ($row= mysqli_fetch_array($result))
{
$name_data=$row['name'];
$name_email=$row['email'];
$name_password=$row['password'];
$name_address=$row['address'];
}
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$email=$_POST['email'];
$password=$_POST['password'];
$address=$_POST['address'];
if(empty($name))
{
//if the value is empty its going to set it equal to the database value
$name=$name_data;
}
if(empty($email))
{
$email=$name_email;
}
if ($password == '')
{
$password=$name_password;
}
if(empty($address))
{
$address=$name_address;
}
}
echo mysqli_errno($con) . ": " . mysqli_error($con) . "\n";
$sql = "UPDATE user SET name='".$name."',email='".$email."',password='".$password."',address='".$address."' WHERE id ='".$id."'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
//header("Location: admin_user_list.php");
exit;
mysqli_close($con);
On both pages add this line at the top session_start();
Than on the admin_edit_user Add this line $_SESSION['id']=$_GET['id'];
Than on admin_update_user.php add this line $id=$_SESSION['id'];
Than on the same file this file admin_update_user.php you have this line $id=$_GET['id']; remove it.
$sql = "UPDATE user SET name='".$name."',email='".mysqli_real_escape_string($con,$email)."',password='".$password."',address='".mysqli_real_escape_string($con,$address)."' WHERE id ='".$id."'";
I feel you have reserved keyword in query try to change your query to and you are mixing mysql and mysqli.
remove this line echo mysql_errno($con) . ": " . mysql_error($con) . "\n";
$sql = "UPDATE `user` SET `name`='".$name."',`email`='".$email."',`password`='".$password."',`address`='".$address."' WHERE `id` =".$id;
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
header("Location: admin_user_list.php");
exit;
if it dosn't work then print your query and try to run it manually in phpmyadmin or mysql;
$sql = "UPDATE user SET name='".$name."',email='".$email."',password='".$password."',address='".$address."' WHERE id ='".$id."'";
Instead of this, try using this:
$sql = "UPDATE user SET name = '$name', email = '$email', password = '$password', address = '$address' WHERE id = $id";
It is much cleaner and will solve lots of query issues.
EDIT:
The issue is probably with 1 of your variables having ' or ".
when you put it in, it becomes something like this:
$sam = "Sam'";
$sql = " UPDATE user SET name = 'sam'' ";
It detects an additional inverted comma and therefore returns an error.
Related
quick question. I'm a rookie so,
when registration success I want to show <div> with a message(value).
So if everything is alright only then should appear on another .php file with HTML code.
I tried to return it but cannot figure out how to do it in the right way.
NOTE:
Now I'm using global but I want to throw it out.
So I have a function in function.php and if...
function createUser(){
global $welcome;
$connection = connectDB();
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST["passwordConfirm"];
$username = mysqli_real_escape_string($connection, $username);
$email = mysqli_real_escape_string($connection, $email);
$password = mysqli_real_escape_string($connection, $password);
$passwordConfirm = mysqli_real_escape_string($connection, $passwordConfirm);
if($_POST['password'] !== $_POST['passwordConfirm']){
$error = exit("Password does not match.");
}
$hashFormat = "$2y$10$";
$salt = "iusesomecrazystrings22";
$hash = $hashFormat . $salt;
$password = crypt($password, $hash);
$query = "INSERT INTO users(username, email, password) VALUES ('$username', '$email', '$password')";
$result = mysqli_query($connection, $query);
if(!$result){
die("Query FAILED " . mysqli_error($connection));
} else{
$welcome = "Registration Success";
}
}
And in other file I have something like this:
<?php
include 'functions.php';
global $welcome;
if(isset($_POST['submit'])){
createUser();
}
?>
<div class="row justify-content-md-center">
<form action="register.php" method="post">
<div class="form-group">
<input type="text" name="username" class="form-control" placeholder="Username" style="text-align: center" required>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email" style="text-align: center" required>
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="Password" style="text-align: center" required>
</div>
<div class="form-group">
<input type="password" name="passwordConfirm" class="form-control" placeholder="Confirm Password" style="text-align: center" required>
</div>
<div class="row justify-content-md-center">
<input type="submit" name="submit" value="SIGN UP" class="btn btn-primary">
</div>
<p></p>
<div class="row justify-content-md-center">
<?php echo $welcome; ?>
</div>
</form>
</div>
So I did it this way...
How should I return instead of $welcome = "Registration Success";, show it ONLY if $result is true and finally print that message in other file that contains HTML.
You can return $message from the function and receive it like this:
if(isset($_POST['submit'])){
$message = createUser();
}
and modify your function createUser like this:
UPDATED
function createUser()
{
// here is your function's body))))
if ($result) {
return "Registration Success";
}
die("Query FAILED " . mysqli_error($connection));
}
if I understand properly:
In createUser(), instead of:
if(!$result){
die("Query FAILED " . mysqli_error($connection));
} else{
$welcome = "Registration Success";
}
Do this:
if(!$result){
die("Query FAILED " . mysqli_error($connection));
}
return true;
And in the PHP file with the HTML do this:
<?php
include 'functions.php';
$userCreated = false;
if(isset($_POST['submit'])){
$userCreated = createUser();
}
if ($userCreated) { ?>
Here goes your message about successfull user creation, or you can use echo '' and you can skip PHP open close tag
<?php } else { ?>
<div class="row justify-content-md-center">
<form action="register.php" method="post">
...
</form>
</div>
<?php }
?>
With this you dont need to use global, instead you use createUser function's return value, which tells you wheter it was successfull or not.
Have a PHP form for a registration system:
<div class="col-md-6 login-right">
<h2> Register Here </h2>
<form action="registration.php" method="post">
<div class="form-group">
<label>Username</label>
<input type="text" name="user" class="form-control" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary"> Register</button>
</form>
</div>
And a registration.php created:
<?php
session_start();
$con = mysqli_connect('localhost','root', 'test');
mysqli_select_db($con, 'userregistration');
$name = $_POST['user'];
$pass = $_POST['password'];
$s = " select * from usertable where name = '$name'";
$result = mysqli_query($con, $s);
$num = mysqli_num_rows($result);
if($num == 1){
echo " Username Already Taken";
}else{
$reg = " insert into usertable(name , password) values ('$name' , $pass')";
mysqli_query($con, $reg);
echo" Registration Successful";
}
?>
Also have a MySQL database created with Database: userregistration »Table: usertable. And the MySQL not sure, quite new to this isn't being populated with the inputted data from the php. When the data is inputted into the php form it requests the registration.php page which works successfully but doesn't populate the table with the data inputted.
You should be actively checking that the connection is successful first, and then also checking that the query was successfully executed too in order to debug this further.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (mysqli_query($conn, $reg)) {
echo "New record created successfully";
} else {
echo "Error: " . $reg . "" . mysqli_error($conn);
}
You should then also close the connection
Trying to update a record unable to fetch the data from database.Getting a blank page not getting any data from database.
<?php
include 'includes/db.php';
$id = (int)$_GET['appoint_id'];
$sql = "SELECT * FROM appointment WHERE appoint_id = '$id'";
$run = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($run)){
$firstname = $row['first_name'];
$lastname = $row['last_name'];
}
?>
<form class="form-horizontal" action="update.php" method="post" role="form">
<input type='hidden' value='<?=$id;?>' name='appoint_id'>
<div class="body">
<div class="row clearfix">
<div class="col-sm-6 col-xs-12">
<div class="form-group">
<div class="form-line">
<input type="text" class="form-control" value="<?php echo $row['first_name'];?>" name="first_name" id="first_name" required>
</div>
</div>
</div>
<div class="col-sm-6 col-xs-12">
<div class="form-group">
<div class="form-line">
<input type="text" class="form-control" value="<?php echo $row['last_name'];?>" name="last_name" id="last_name" required>
</div>
</div>
</div>
</div>
</div>
</form>
update.php
<?php include 'includes/db.php';
if(isset($_POST['submit_user'])){
$ins_sql = "UPDATE first_name,last_name appointment WHERE appoint_id = '$id' ";
$run_sql = mysqli_query($conn,$ins_sql);
}else {
echo "not updated";
}
?>
Not displaying any errors in error log as well.
update.php has incorrect syntax for the UPDATE query, and it's not using any of the form parameters (except for one that doesn't even exist in the form, $_POST['submit_user']).
You should use a prepared statement to protect against SQL injection.
<?php
include 'includes/db.php';
$ins_sql = "UPDATE appointment
SET first_name = ?, last_name = ?
WHERE appoint_id = ?";
$stmt = $conn->prepare($ins_sql);
$stmt->bind_param("ssi", $_POST['first_name'], $_POST['last_name'], $_POST['appoint_id']);
if ($stmt->execute()) {
echo "updated";
} else {
echo "not updated";
}
?php session_start();
include 'includes/db.php';
$id = (int)$_GET['id'];
$sql = "SELECT * FROM appointment WHERE appoint_id = $id";
$oppointArr =array();
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$oppointArr = $row;
echo "Name: " . $row["first_name"]. "<br>";
}
} else {
echo "0 results";
}
//mysqli_close($conn);
?>
Query for fetching the data for a particular record
Good day.
So below i have a php script that is supposed to query my db and look for user details. the db is set up and the data is available in it. the issue here seems that once i click the submit button with my user entered details, it fails on the first if statement, to see if the email exists. i am not sure why.
But here is the submit form.
<form action = "submit2.php" method="Post" >
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="email">Email</label> -->
<input type="text" id="email" name="email" class="form-control" placeholder="Your user name">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="subject">Subject</label> -->
<input type="text" id="password" name="password" class="form-control" placeholder="Your Password">
</div>
</div>
<div class="form-group">
<input type="submit" value="Login" class="btn btn-primary">
</div></form>
and here is the submit2.php that is supposed to manipulate the data from the form and query the db.
<?php
session_start();
require_once('connect.php');
if(isset($_POST) & !empty($_POST)){
$useremail = mysqli_real_escape_string($connection,$_POST['email']);
$userpassword = mysqli_real_escape_string($connection, $_POST['password']);
if (empty($useremail) || empty($userpassword)){
header("Location: customerportal.php?login=empty");
exit();
}
else{
$sql = "SELECT * FROM 'USERS' where EMAIL ='$useremail';";
$emailresult = mysqli_query($connection, $sql);
$emailresultcheck = mysqli_num_rows($emailresult);
//check if email exists
if($emailresultcheck == 0){
header("Location: customerportal.php?login=invalidEmail");
}
else {
if($row = mysqli_fetch_assoc($emailresult)){
//dehash the password
$hashedPWDCheck = password_verify($userpassword,$row['ENCRYPTEDPWD']);
if($hashedPWDCheck == false){
header("Location: customerportal.php?login=passwordincorrect");
exit();
}
elseif($hashedPWDCheck == true){
$_SESSION['email'] = $email;
// header("Location: Landingpage.php");
echo "Success";
}
}
else{
header("Location: customerportal.php?login=invalid");
exit();
}
}
}
}
?>
The submit always fails else statement and returns the invalidEmail header location and i am not sure why. the Connection file is below.what am i missing?
<?php
$connection = mysqli_connect("localhost", "root", "");
if(!$connection){
echo "Failed to connect database" . die(mysqli_error($connection));;
}
$dbselect = mysqli_select_db($connection, "dhctest");
if(!$dbselect){
echo "Failed to Select database" . die(mysqli_error($connection));
}
?>
Change this
$sql = "SELECT * FROM 'USERS' where EMAIL = '$useremail';";
to this
$sql = "select * from users where email = $useremail";
Okay, so solved the issue, by running a var_dump() on everyone of my variables until i came across the error that was being outputted by my sql code.
On the line
$sql = "SELECT * FROM 'USERS' where EMAIL = '$useremail';";
I had to remove the '' and replace with ``.
And that seems to have solved the issue.
Thank you for everyone who assisted.
I have thoroughly researched my topic before coming here and can't seem to figure out my problem.
I have an HTML page:
<form role="form" action="register.php" method="POST">
<div class="form-group">
<label>First Name:</label>
<input type="text" name="first_name">
</div>
<div class="form-group">
<label>Last Name:</label>
<input type="text" name="last_name">
</div>
<div class="form-group">
<label>Student ID:</label>
<input type="number" name="student_id">
</div>
<div class="form-group">
<label>Email address:</label>
<input type="email" name="email">
</div>
<button type="submit" name="register" value="register">Register</button>
</form>
<form role="form" action="login.php" method="POST">
<div class="form-group">
<label>Email address:</label>
<input type="email" name="email">
</div>
<button type="submit" name="login" value="login">Login</button>
</form>
This functions and communicates perfectly well with my login page written in php, it checks if the submitted email address already exists in a MySQL database. It will then point the user to a profile page and the code exits itself.
My issue is with my register page, I use the same MySQL SELECT functions that I do on my login page, to check and see if the submitted student ID or email already exists in the database and if so, will return back to the form for the user to try again:
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$student_id = $_POST['student_id'];
$email = $_POST['email'];
if (isset($_POST['register'])) {
register($conn, $first_name, $last_name, $student_id, $email);
}
function register($conn, $first_name, $last_name, $student_id, $email) {
$Ssql = "SELECT student_id FROM AidenLocke where student_id = '$student_id'";
$Sresult = mysqli_query($conn, $sql);
if (mysqli_num_rows($Sresult) > 0) {
header('Location: form.html');
} else {
$sql = "INSERT INTO AidenLocke (first_name, last_name, email, student_id)
VALUES ('$first_name', '$last_name', '$email', '$student_id')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br />" . $conn->error;
}
header('Location: profile.php');
}
}
(I have removed my database information for security reasons but there is no connection problem)
My main issue is with the else section of the second if statement, my code does not check if the student id already exists, and regardless of what information I enter into the form, makes a new entry in to the database.
I am quite confused and hoping someone can give me a valid answer, thanks!
You seem to have a typo in your variable when you query the database:
$Ssql = "SELECT student_id FROM AidenLocke where student_id = '$student_id'";
^^^^
$Sresult = mysqli_query($conn, $sql);
^^^
That is, you're using $sql instead of $Ssql