I have a little Problem with my Update query to chnage the Profile Infos
Problem now:
My Update Query is not working completly, the E-Mail query work but the status query is not working.
PHP CODE
if(!empty($_POST)) {
$query = "UPDATE users SET";
if(!empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && $_POST['email'] != $_SESSION['u']['email']) {
$s_mail = $_POST['email'];
$row = mysql_num_rows(mysql_query("SELECT email FROM users WHERE email='$s_mail'"));
if($row != 0) {
header("Location: ".$l['settings']."?msg=2");
die("REDIRECT");
}
$query .= " `email`='".$_POST['email']."'";
$_SESSION['u']['email'] = $_POST['email'];
} else if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
header("Location: ".$l['settings']."?msg=3");
die("REDIRECT");
}
//PROBLEM starts here
if(!empty($_POST['status'])) {
$query .= ",`status`='".$_POST['status']."'";
$_SESSION['u']['status'] = $_POST['status'];
}
//AND ends here
$query .= " WHERE id='".$_SESSION['u']['id']."'";
mysql_query($query);
header("Location: ".$l['settings']."?msg=1");
die("REDIRECT");
}
HTML FORM
<input maxlength="200" type="text" class="form-control" placeholder="Status" name="status" value="<?php //ECHO STATUS ?>" />
Maybe someone can help me.
On your $query you have
$query .= ",`status`='".$_POST['status']."'";
remove comma make it like this
$query .= " `status`='".$_POST['status']."'";
You need to set a flag for email condition as
$flag = FALSE;// set a flag
if (!empty($_POST)) {
if (!empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && $_POST['email'] != $_SESSION['u']['email']) {
$s_mail = $_POST['email'];
$row = mysql_num_rows(mysql_query("SELECT email FROM users WHERE email='$s_mail'"));
if ($row != 0) {
header("Location: " . $l['settings'] . "?msg=2");
die("REDIRECT");
}
$flag = TRUE;// set to true if success
$_SESSION['u']['email'] = $_POST['email'];
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
header("Location: " . $l['settings'] . "?msg=3");
die("REDIRECT");
}
//PROBLEM starts here
if (!empty($_POST['status'])) {
$query = "UPDATE users SET";
$query .= " `status`='" . $_POST['status'] . "'";
if ($flag) {// if true then apply email condition
$query .= ",`email`='" . $_POST['email'] . "'";
}
$query .= " WHERE id='" . $_SESSION['u']['id'] . "'";
$_SESSION['u']['status'] = $_POST['status'];
}
//AND ends here
mysql_query($query);
header("Location: " . $l['settings'] . "?msg=1");
die("REDIRECT");
}
Note:- mysql is deprecated instead use mysqli OR pdo
Related
I am making a hotel booking system for a school project.
Guests first need to create an account:
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$signupdate = mysqli_real_escape_string($conn, $_POST['signupdate']);
$first = mysqli_real_escape_string($conn, $_POST['firstname']);
$last = mysqli_real_escape_string($conn, $_POST['lastname']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$phone = mysqli_real_escape_string($conn, $_POST['phone']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$hoteluserkey = uniqid('', true);
//Error handlers
//Check for empty fields
if (empty($signupdate) || empty($first) || empty($last) || empty($email) || empty($phone) || empty($address) || empty($pwd)) {
header("Location: ../index.php?signup=empty");
exit();
} else {
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
header("Location: ../index.php?signup=invalid");
exit();
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../index.php?signup=invalidemail");
exit();
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
//Insert the user into the database
$sql = "INSERT INTO hotelusers
(hotelusers_signupdate, hotelusers_hoteluserkey, hotelusers_first, hotelusers_last, hotelusers_email, hotelusers_phone, hotelusers_address, hotelusers_pwd)
VALUES ('$signupdate', '$hoteluserkey', '$first', '$last', '$email', '$phone', '$address', '$hashedPwd');";
mysqli_query($conn, $sql);
header("Location: ../index.php?signup=success");
exit();
}
}
}
} else {
header("Location: ../index.php");
exit();
}
This code works.
Now to problem comes. When someone books a room they see these input fields:
<div class="book">
<p class="main_p_ex">Book a room</p>
<form class="book" action="includes/book.inc.php" method="post">
<input type="hidden" name="bookdate" value="<?php echo date("Y-m-d h:i:sa"); ?>">
<input type="text" name="userkey" placeholder="your key">
<input type="password" name="pwd" placeholder="password">
<p>room</p>
<select name="room">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
<option value="6">six</option>
<option value="7">seven</option>
<option value="8">eight</option>
<option value="9">nine</option>
<option value="10">ten</option>
</select>
<p>from</p>
<input type="date" name="from" min="<?php echo date("Y-m-d");?>">
<p>to</p>
<input type="date" name="to" min="<?php echo date("Y-m-d");?>">
<textarea name="otherguests" placeholder="full names of all other
guests"></textarea>
<textarea name="comments" placeholder="any comments?"></textarea>
<button type="submit" name="submit">Book!</button>
</form>
</div>
This also works fine.
I have this code for inserting these inputs into a database:
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$bookdate = mysqli_real_escape_string($conn, $_POST['bookdate']);
$userkey = mysqli_real_escape_string($conn, $_POST['userkey']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$room = mysqli_real_escape_string($conn, $_POST['room']);
$from = mysqli_real_escape_string($conn, $_POST['from']);
$to = mysqli_real_escape_string($conn, $_POST['to']);
$otherguests = mysqli_real_escape_string($conn, $_POST['otherguests']);
$comments = mysqli_real_escape_string($conn, $_POST['comments']);
$bookingkey = uniqid('', true);
//Error handlers
//Check if inputs are empty
if (empty($userkey) || empty($pwd) || empty($room) || empty($from) || empty($to) || empty($pwd)) {
header("Location: ../index.php?login=empty");
exit();
} else {
$sql = "SELECT * FROM hotelusers WHERE hotelusers_hoteluserkey='$userkey'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
header("Location: ../index.php?key=error");
exit();
} else {
if ($row = mysqli_fetch_assoc($result)) {
//De-hashing the password
$hashedPwdCheck = password_verify($pwd, $row['hotelusers_pwd']);
if ($hashedPwdCheck == false) {
header("Location: ../index.php?key=error");
exit();
} elseif ($hashedPwdCheck == true){
$sql = "SELECT * FROM hotelrooms WHERE hotelrooms_id='$room'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$roomnew = $row['hotelrooms_name']; }
}
$fromnew = strtotime($from);
$tonew = strtotime($to);
$datediff = $tonew - $fromnew;
$days = round($datediff / 86400);
$sql = "SELECT * FROM hotelrooms WHERE hotelrooms_id='$room'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$pricepd = $row['hotelrooms_price']; }
}
$price = $days * $pricepd;
echo $roomnew . " -- " . $price . " -- " . $days . " -- " . $bookdate . " -- " . $userkey . " -- " . $room . " -- " . $otherguests . " -- " . $comments;
$sql = "INSERT INTO hotelbookings
(hotelbooking_bookingkey, hotelbooking_bookdate, hotelbooking_userkey, hotelbooking_room, hotelbooking_from, hotelbooking_to, hotelbooking_days, hotelbooking_price, hotelbooking_paid, hotelbooking_otherguests, hotelbooking_comments)
VALUES ('$bookingkey', '$bookdate', '$userkey', '$roomnew', '$from', '$to', '$days', '$price', '$otherguests', '$comments');";
mysqli_query($conn, $sql);
//header("Location: ../index.php?booking=success");
exit();
}
}
}
}
} else {
header("Location: ../index.php?booking=error");
exit();
}
NOTE: I disabled the last header function for debugging. Un-commenting it changes nothing. Also tried clearing browser history, cookies and all that. Nothing works.
What am I missing here?
I don't get any errors, and the echo $roomnew . " -- " . $price . " -- " . $days . " -- " . $bookdate . " -- " . $userkey . " -- " . $room . " -- " . $otherguests . " -- " . $comments; works fine. It just doesn't insert anything.
solved it myself by just making everything again... kinda weird I know
<?php
if (isset($_GET['action']) && ($_GET['action'] == 'submit')) {
$name = $_POST['name'];
$message = $_POST['message'];
$email = $_POST['email'];
$ip = $_SERVER["REMOTE_ADDR"];
$messageip = "User IP: $ip\n\n" . $messageip;
$sql = "SELECT * FROM tbl_user WHERE email = '" . $email . "'";
$query = mysql_query($sql);
$count = mysql_num_rows($query);
if ($count >= 1) {
echo "User Already in Exists<br/>";
} else {
$newUser = "INSERT INTO tbl_user(name,message,email,ip_address) values('$name','$message','$email','$messageip')";
$query2 = mysql_query($newUser);
if ($query2) {
echo "You are now registered<br/>";
} else {
echo "Error adding user in database<br/>";
}
}
echo $name . '<br/>';
echo $message . '<br/>';
echo $email . '<br/>';
echo $messageip . '<br/>';
}
?>
I am using this code to capture the ip address but i cannot get the machine ip of the particular user from which i can display the address by dynamically, so can anyone help me out on this topic?
You seem to be concatenating a wrong (empty) var.
Try changing this:
$messageip = "User IP: $ip\n\n" . $messageip;
to this:
$messageip = "User IP: $ip\n\n" . $ip;
I am very new to PHP (currently doing a university project). My website is an admin site, with about 3 admin users who can log in and change the site etc. Currently, I have a delete function on my comments (comments which users can post to the site) but anybody who comes onto the site can see the delete function and can delete anybodies comments?
I want it so that only my admin's when logged in, can see the delete function, and subsequently be the only ones who can delete the comments. I have a users database with name, password, username and email columns. I was wondering if somebody could please take a look at my code and tell me how I can change this so that only when admins log in they can see the button and delete the comments.
$str_message = "";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
}else{
//if ($_SESSION['admin'] == 'yes') {
if(isset($_GET['delete'])){
$deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
$deleter=mysqli_query($db_server, $deleteq);
IF($deleter){
echo"<p>That message was deleted!</p>";}}
//}
//Test whether form has been submitted
if(trim($_POST['submit']) == "Submit"){
//Handle submission
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it
again.
(reCAPTCHA said: " . $resp->error . ")";
} else {
// Your code here to handle a successful verification
$comment = $_POST['comment'];
if($comment != ""){
$query = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query) or die("Comment insert failed: " .
mysqli_error($db_server) );
$str_message = "Thanks for your comment!";
}else{
$str_message = "Invalid form submission";
}
}
}
//Create page with or without submission
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) );
{
while($row = mysqli_fetch_array($result)){
$ID= $row['ID'];
$str_result .= "<p><em>Comment $j (" . $row['commDate'] .
")</em><br /> " .$row['comment'] . "</p>
<a href ='commentnow.php?delete=$ID
'>Delete</a><hr />";
}
mysqli_free_result($result);
} }
?>
If we assume that your commented out statement to check if the user is an admin (if ($_SESSION['admin'] == 'yes')) works, then the following code should give you a good idea of how to do it. There are two places where you need to add the if statement. I haven't been able to test this but look in this code for where you see // ADMIN IF STATEMENT and I hope you understand what changes to your code need to be made for it to work properly.
<?
$str_message = "";
if (!$db_server) {
die("Unable to connect to MySQL: " . mysqli_connect_error());
} else {
if ($_SESSION['admin'] == 'yes') { // ADMIN IF STATEMENT
if (isset($_GET['delete'])) {
$deleteq = "DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
$deleter = mysqli_query($db_server, $deleteq);
if ($deleter) {
echo "<p>That message was deleted!</p>";
}
}
}
//Test whether form has been submitted
if (trim($_POST['submit']) == "Submit") {
//Handle submission
$resp = recaptcha_check_answer(
$privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]
);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it again. (reCAPTCHA said: " . $resp->error . ")";
} else {
// Your code here to handle a successful verification
$comment = $_POST['comment'];
if ($comment != "") {
$query = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query) or die("Comment insert failed: " . mysqli_error($db_server) );
$str_message = "Thanks for your comment!";
} else {
$str_message = "Invalid form submission";
}
}
}
//Create page with or without submission
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) ); {
while ($row = mysqli_fetch_array($result)) {
$ID = $row['ID'];
if ($_SESSION['admin'] == 'yes') { // ADMIN IF STATEMENT
$str_result .= "<p><em>Comment $j (" . $row['commDate'] . ")</em><br /> " .$row['comment'] . "</p><a href ='commentnow.php?delete=$ID'>Delete</a><hr />";
} else {
$str_result .= "<p><em>Comment $j (" . $row['commDate'] . ")</em><br /> " .$row['comment'] . "</p>";
}
}
mysqli_free_result($result);
}
}
?>
if ($_SESSION['admin'] == 'yes') {
<insert code to generate a delete button here>
}
First you need to change in your log in page. When an user login then check if he is an admin user. if yes the set a session variable ($_SESSION['admin']) to yes or set it to no. try like this:
//login.php
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
}else{
session_start();
$sql="Select * FROM users WHERE user_name = 'your_username' and LIMIT 1";
$result=mysqli_query($db_server, $sql);
$objUser = $result->fetch_object();
if($objUser->user_type =="admin")
$_SESSION['admin'] = 'yes';
else
$_SESSION['admin'] = 'no';
//rest of your code for login the user
}
Then in your delete page check if current user is admin or not. If yes then execute query else echo a message. like this:
session_start();
$str_message = "";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
}else{
if(isset($_GET['delete'])){
if ($_SESSION['admin'] == 'yes') {
$deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
$deleter=mysqli_query($db_server, $deleteq);
if($deleter){
echo"<p>That message was deleted!</p>";}
}
else
{
echo "you are not admin";
}
}
//Test whether form has been submitted
if(trim($_POST['submit']) == "Submit"){
//Handle submission
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it
again.
(reCAPTCHA said: " . $resp->error . ")";
} else {
// Your code here to handle a successful verification
$comment = $_POST['comment'];
if($comment != ""){
$query = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query) or die("Comment insert failed: " .
mysqli_error($db_server) );
$str_message = "Thanks for your comment!";
}else{
$str_message = "Invalid form submission";
}
}
}
//Create page with or without submission
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) );
{
while($row = mysqli_fetch_array($result)){
$ID= $row['ID'];
$str_result .= "<p><em>Comment $j (" . $row['commDate'] .
")</em><br /> " .$row['comment'] . "</p>
<a href ='commentnow.php?delete=$ID
'>Delete</a><hr />";
}
mysqli_free_result($result);
} }
?>
I think it makes sense !
I have been designing a website and everything has been working perfectly, until I started adding in little extras so it would work EXACTLY how I wanted it to work.
This is the script for a website that uploads a title, description, name of a person, image, email address and password for the advert that they are putting online. However it no longer wants to correctly name the image and it sends out an email twice, once in the instance that there may be an image and it instantly does it in the instance where someone may not upload an image, but it is reading it as if it is doing both because there is an error with the file upload.
Btw this is the first PHP script I have ever created so it may seem mashy as I have been kind of mixing it up from different things that I have found online :)
p.s the page where the magic happens is www.afterswap.com/give.php
p.p.s I have a global config file that sets all of the DB connection info etc, hence it being non-existent here.
<?PHP
include("inc/header.php");
foreach ($_POST as $key => $val)
$_POST[$key] = mysqli_real_escape_string($con, $val);
$back = "<a href='give.php'>Click Here To Go Back And Try Again</a>";
if (isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) {
$title = mysqli_real_escape_string($title123);
$title123 = mysqli_real_escape_string($_POST['title']);
$description = mysqli_real_escape_string($description123);
$description123 = mysqli_real_escape_string($_POST['description']);
$Sell_by = $_POST['Sell_by'];
$name = mysqli_real_escape_string($name123);
$name123 = mysqli_real_escape_string($_POST['name']);
$email = $_POST['email'];
$password = $_POST['password'];
$imagename = basename($_FILES['userfile']['name']);
$uploadedfile = $_FILES['userfile']['tmp_name'];
if (empty($imagename)) {
$error = 1;
echo "<h2 class='error'>The name of the image was not found.</h2>" . $back;
}
if ($error != 1 && $noimg != 1) {
$filename = stripslashes($_FILES['userfile']['name']);
$extension = substr(strrchr($filename, '.'), 1);
$extension = strtolower($extension);
}
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
echo '<h2 class="error">Error. Images Must Be Jpg, Gif, or Png Format! Please Go Back And Try Another Image.</h2>' . $back . '';
$errors = 1;
} else {
$time = time();
$newimage = "/photos/" . $time . $imagename;
$result = move_uploaded_file($_FILES['userfile']['tmp_name'], $newimage);
if (empty($result)) {
$error = 1;
echo "<h2 class='error'>There was an error uploading your image.</h2><br/>" . $back . "";
}
$date = date("Y/m/d H:i:s");
$query = "INSERT INTO classifieds (adid, title, description, Sell_by, name, email, password, picture, date, views, authorized ) VALUES ('', '$title123', '$description123', '$Sell_by', '$name123', '$email', '$password', '$newimage', '$date', '0', '0')";
mysqli_query($query) or die(mysqli_error());
$pullback = "SELECT * FROM classifieds WHERE title = '$title123' AND email ='$email' limit 1";
$query2 = mysqli_query($pullback) or die(mysqli_error());
while ($row = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
$newid = $row['adid'];
$pass = $row['pass'];
}
$url = "http://";
$url .= getenv("HTTP_HOST");
$Name = "AfterSwap";
$emailf = "noreply#afterswap.com";
$recipient = $email;
$mail_body = "Thank you for posting a new listing!<br /><br />You May Now Manage Your Ad by selecting one of the following options:<br /><br />Approve your listing: <a href='" . $url . "/approve.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Edit your listing: <a href='$url/edit.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Remove your listing: <a href='" . $url . "/remove.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br /><br />Regards,<br /><br />The AfterSwap Team";
$subject = "AfterSwap Ad Details";
$headers = "From: " . $Name . " <" . $emailf . ">\r\n";
$headers .= "Content-type: text/html\r\n";
mail($recipient, $subject, $mail_body, $headers);
echo "<div align='justify'><div class='success'>Your listing '" . $name123 . "' Has Been Submitted Successfully! <br/><br/>Please take note: Your listing will not show on the website until you verify it via the email sent to you. This email also allows you to edit and remove your listing as well.</div></div>";
}
} elseif (isset($_POST['upload'])) {
$title = mysqli_real_escape_string($title123);
$title123 = mysqli_real_escape_string($_POST['title']);
$description = mysqli_real_escape_string($description123);
$description123 = mysqli_real_escape_string($_POST['description']);
$Sell_by = $_POST['Sell_by'];
$name = mysqli_real_escape_string($name123);
$name123 = mysqli_real_escape_string($_POST['name']);
$email = $_POST['email'];
$password = $_POST['password'];
$date = date("Y/m/d H:i:s");
$query = "INSERT INTO classifieds (adid, title, description, cat, Sell_by, name, email, password, picture, date, views, authorized ) VALUES ('', '$title123', '$description123', '$category', '$Sell_by', '$name123', '$email', '$password', 'images/noimage.jpg', '$date', '0', '0')";
mysqli_query($query) or die(mysqli_error());
$pullback = "SELECT * FROM classifieds WHERE title = '$title123' AND email ='$email' limit 1";
$query2 = mysqli_query($pullback) or die(mysqli_error());
while ($row = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
$newid = $row['adid'];
$pass = $row['pass'];
}
$url = "http://";
$url .= getenv("HTTP_HOST");
$Name = "AfterSwap";
$emailf = "noreply#afterswap.com";
$recipient = $email;
$mail_body = "Thank you for posting a new listing!<br /><br />You May Now Manage Your Ad by selecting one of the following options:<br /><br />Approve your listing: <a href='" . $url . "/approve.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Edit your listing: <a href='$url/edit.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Remove your listing: <a href='" . $url . "/remove.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br /><br />Regards,<br /><br />The AfterSwap Team";
$subject = "AfterSwap Ad Details";
$headers = "From: " . $Name . " <" . $emailf . ">\r\n";
$headers .= "Content-type: text/html\r\n";
mail($recipient, $subject, $mail_body, $headers);
echo "<div align='justify'><div class='success'>Thank you " . $name123 . ", your listing has been submitted successfully! <br/><br/>Please take note: Your isting will not show on the website until you verify it via the email sent to you. This email also allows you to edit and remove your listing as well.</div></div>";
} else {
?>
/* HTML Form here */
<?PHP } ?>
Try this
Change this line
} elseif (isset($_POST['upload'])) {
to
} elseif (isset ( $_POST ['upload'] ) && empty($_FILES)) {
The only thing I can think of would be a if, elseif, or else being passed twice because the condition is being met twice. You may want to revise the code with better indentation, and checking when the elseif, if, and else blocks are passed. Also, it would be a really good idea to take the advice from the two people that commented on your post, MYSQLI is a great way to go! One more thing: You should never pass $_POST unsanitized!! Here is a short easy sanitization script!
MYSQLI:
foreach($_POST as $key=>$val)
$_POST[$key] = mysqli_real_escape_string($con, $val);
MYSQL:
foreach($_POST as $key=>$val)
$_POST[$key] = mysql_real_escape_string($con, $val);
I am having two problems with my code below.
<?php
$validSubmission = isset($_POST['resetpass']) && $_POST['students'] && $_POST['newpass'] && $_POST['confirmpass'];
$sql = "SELECT StudentUsername, StudentForename, StudentSurname FROM Student ORDER BY StudentUsername";
$sqlstmt = $mysqli->prepare($sql);
$sqlstmt->execute();
$sqlstmt->bind_result($dbStudentUsername, $dbStudentForename, $dbStudentSurname);
$students = array(); // easier if you don't use generic names for data
$studentHTML = "";
$studentHTML .= '<select name="students" id="studentsDrop">' . PHP_EOL;
$studentHTML .= '<option value="">Please Select</option>' . PHP_EOL;
$outputstudent = "";
while ($sqlstmt->fetch())
{
$student = $dbStudentUsername;
$firstname = $dbStudentForename;
$surname = $dbStudentSurname;
if (!$validSubmission && isset($_POST['students']) && $student == $_POST['students'])
{
$studentHTML .= "<option value='" . $student . "' selected='selected'>" . $student . " - " . $firstname . " " . $surname . "</option>" . PHP_EOL;
}
else
{
$studentHTML .= "<option value='" . $student . "'>" . $student . " - " . $firstname . " " . $surname . "</option>" . PHP_EOL;
}
}
$studentHTML .= '</select>';
$errormsg = (isset($errormsg)) ? $errormsg : '';
if (isset($_POST['resetpass']))
{
//get the form data
$studentdrop = (isset($_POST['students'])) ? $_POST['students'] : '';
$newpass = (isset($_POST['newpass'])) ? $_POST['newpass'] : '';
$confirmpass = (isset($_POST['confirmpass'])) ? $_POST['confirmpass'] : '';
//make sure all data was entered
if ($studentdrop != "")
{
if ($newpass)
{
if (strlen($newpass) <= 5)
{
$errormsg = "Your Password must be a minimum of 6 characters or more";
}
else
{
if ($confirmpass)
{
if ($newpass === $confirmpass)
{
//Make sure password is correct
$query = "SELECT StudentUsername FROM Student WHERE StudentUsername = ?";
// prepare query
$stmt = $mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s", $username);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbStudentUsername);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
if ($numrows == 1)
{
//encrypt new password
$newpassword = md5(md5("93w" . $newpass . "ed0"));
//update the db
$updatesql = "UPDATE Student SET StudentPassword = ? WHERE StudentUsername = ?";
$update = $mysqli->prepare($updatesql);
$update->bind_param("ss", $newpassword, $username);
$update->execute();
//make sure the password is changed
$query = "SELECT StudentUsername, StudentPassword FROM Student WHERE StudentUsername = ? AND StudentPassword = ?";
// prepare query
$stmt = $mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("ss", $username, $newpassword);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbStudentUsername, $dbStudentPassword);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
if ($numrows == 1)
{
$errormsg = "<span style='color: green'>Student " . $student . " - " . $firstname . " " . $surname . " has been Registered</span>";
}
else
{
$errormsg = "An error has occured, the Password was not Reset";
}
}
}
else
{
$errormsg = "Your New Password did not Match";
}
}
else
{
$errormsg = "You must Confirm your New Password";
}
}
}
else
{
$errormsg = "You must Enter your New Password";
}
}
else if ($studentdrop == "")
{
$errormsg = "You must Select a Student";
}
}
I am trying to create a rest password page where an admin can reset a student's password.
PROBLEM 1:
In my code what I am trying to do is that if a php validation message appears (one of the $errormsg appears except for the $errormsg which displays the sucess message), then the students drop down menu should still display the option that was selected after the submission of the form occurs. Now this works for all the validation message where the user has left a text input blank, but the only validation message it doesn't work for is when the user has not typed in matching passwords for the new and confirm passwords. If the $errormsg = "Your New Password did not Match";
occurs then the students drop down menu goes back to the Please Select option. How come it goes back to the Please Select option everytime this validation message appears and how can I keep the selected student still selected if this validation occurs?
PROBLEM 2:
If I successfully enter in all the details and submit, it does not perform the insert, yet it does not display the fail message $errormsg = "An error has occured, the Password was not Reset";
or the success message $errormsg = "<span style='color: green'>Student " . $student . " - " . $firstname . " ". $surname . " has been Registered</span>";, why is this occuring? I know the UPDATE statement is correct as I tested this in phpmyadmin.
$username (line 72 and onwards) is never set. I presume this should come from '$studentdrop'?
This means you update where StudentUsername == '', which will fail.
To help you debug:
1. Turn on warning and notices in the error handler for writing code ( error_reporting(E_ALL); ) as it will reveal problems like this
2. As opposed to constantly counting the rows, you can save time in that the bind_result/store_value won't work unless you got a result. So you can check that value you get in bind_result - and if you had checked that `$dbStudentUsername == $username` in line 78, then it would have also thrown a wobbly at that stage.
3. When you've done the "update", you can check the number of "affected rows"; if this > 0 then the password has been updated; no need for a secondary DB query.
Hope that helps