PHP Delete comments button - php

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 !

Related

Displaying ALL data from sql table in PHP?

When I print my code it only prints the question and description of id = 1 but not the rest of the table.
here is my code.
Please show me how to print my entire table which has like 20 questions or so...and also please show me how to make it so that the questions stay on the browser (even when I refresh the page) because currently the data does not stay on the browser when i refresh the page.
Thanks So Much!
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
} else {
echo "failed to fetch array";
}
}
?>
You need a for each loop:
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
} else {
echo "failed to fetch array";
}
}
?>
All I've done there is change:
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
to:
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
fetch_assoc() — Fetch a result row as an associative array
so it gets only 1 row you need to loop through the rest of the rows check the examples reference from php docs

All-in-One Web form

I'm learning PHP and I am now on creating an all in one web form that adds a new subscriber record to the subscribers table in the newsletter database. This is my first time on this site, so excuse any n00biness.
The comments explain the portion of code which determines whether the form will be processed. I'm not sure if it needs to go inside the if..else statement that validates the submitted form data, or if it goes after the validation in its own if..else.
When I put it inside the validation, the html form shows, but when I hit submit, all the info refreshes and nothing happens.
When I put it after the validation, the html form does not show, I get an error saying undefined variable: FormErrorCount. It then tells gives me the id number I'm supposed to get, but I did not enter a name or email (due to the html form not showing) and that is left blank.
There is an include file, but that is just fine.
I'm sure once this gets figured out, I will have the feeling to want to slap myself, but I have been staring at the screen way too long. Thank you
<?php
$ShowForm = FALSE;
$SubscriberName = "";
$SubscriberEmail = "";
if (isset($_POST['submit'])) {
$FormErrorCount = 0;
if (isset($_POST['SubName'])) {
$SubscriberName = stripslashes($_POST['SubName']);
$SubscriberName = trim($SubscriberName);
if (strlen($SubscriberName) == 0) {
echo "<p>You must include your name</p>\n";
++$FormErrorCount;
}
}else{
echo "<p>Form submittal error (No 'SubName' field)!</p>\n";
++$FormErrorCount;
}
if (isset($_POST['SubEmail'])) {
$SubscriberEmail = stripslashes($_POST['SubEmail']);
$SubscriberEmail = trim($SubscriberEmail);
if (strlen($SubscriberEmail == 0)) {
echo "<p>You must include your email address!</p>\n";
++$FormErrorCount;
}
}else{
echo "<p>Form submittal error (No 'SubEmail' field)!</p>\n";
++$FormErrorCount;
}
//CODE BELOW IS THE SAME AS THE COMMENTED OUT CODE TOWARDS THE END. NOT SURE WHERE IT GOES.
if ($FormErrorCount == 0) {
$ShowForm = FALSE;
include("inc_db_newsletter.php");
if ($DBConnect !== FALSE) {
$TableName = "subscribers";
$SubscriberDate = date("Y-m-d");
$SQLstring = "INSERT INTO $TableName " .
" (name, email, subscribe_date) " .
" VALUES('$SubscriberName', '$SubscriberEmail', '$SubscriberDate')";
$QueryResult = #mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE) {
echo "<p>Unable to insert the values into the subscriber table.</p>" .
"<p>Error code " . mysql_errno($DBConnect) . ": " .
mysql_error($DBConnect) . "</p>";
}else{
$SubscriberID = mysql_insert_id($DBConnect);
echo "<p>" . htmlentities($SubscriberName) . ", you are now subscribed to our
newsletter.<br />";
echo "Your subscriber ID is $SubscriberID.<br />";
echo "Your email address is " . htmlentities($SubscriberEmail) . ".</p>";
}
mysql_close($DBConnect);
}
}else{
$ShowForm = TRUE;
}
//CODE ABOVE IS THE SAME AS THE COMMENTED OUT CODE TOWARDS THE END. NOT SURE WHERE IT GOES.
}else{
$ShowForm = TRUE;
}
/* CODE BELOW IS SAME AS THE CODE BETWEEN THE COMMENTS ABOVE, BUT NOT SURE WHERE IT BELONGS
if ($FormErrorCount == 0) {
$ShowForm = FALSE;
include("inc_db_newsletter.php");
if ($DBConnect !== FALSE) {
$TableName = "subscribers";
$SubscriberDate = date("Y-m-d");
$SQLstring = "INSERT INTO $TableName (name, email, subscribe_date) " .
"VALUES ('$SubscriberName', '$SubscriberEmail', '$SubscriberDate')";
$QueryResult = #mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE) {
echo "<p>Unable to insert the values into the subscriber table.</p>" .
"<p>Error code " . mysql_errno($DBConnect) . ": " .
mysql_error($DBConnect) . "</p>";
}else{
$SubscriberID = mysql_insert_id($DBConnect);
echo "<p>" . htmlentities($SubscriberName) . ", you are now subscribed to our
newsletter.<br />";
echo "Your subscriber ID is $SubscriberID.<br />";
echo "Your email address is " . htmlentities($SubscriberEmail) . ".</p>";
}
mysql_close($DBConnect);
}
}else{
$ShowForm = TRUE;
}
*/CODE ABOVE IS SAME AS THE CODE BETWEEN THE COMMENTS ABOVE SECTION, BUT NOT SURE WHERE IT BELONGS
//HTML PORTION
if ($ShowForm) {
?>
<form action = "NewsletterSubscribe.php" method = "POST">
<p><strong>Your Name: </strong>
<input type = "text" name = "SubName" value = "<?php echo $SubscriberName; ?>" /></p>
<p><strong>Your Email Address: </strong>
<input type = "text" name = "SubEmail" value = "<?php echo $SubscriberEmail; ?>" /></p>
<p><input type = "Submit" name = "Submit" value = "Submit" /></p>
</form>
<?php
}
?>
Your code, ignoring for now the ShowForm part at the end, is structured like this:
if this is a submit {
validate the form data
if there are no errors {
save the form data
}
}
This looks reasonable. Maybe your form isn't being submitted as a POST? Check your <form action> and also use Firebug to make sure the form data is being submitted.
If you were to move the error check, you would have:
if this is a submit {
validate the form data
}
if there are no errors {
save the form data
}
And that's wrong because if the form were not being submitted, then you'd have no errors (hence the "undefined variable" error) and then it would attempt to save the nonexistent form data.

PHP/Mysql Create thread then redirect to forum category

Basically I have edited the "new_topic" page in my generic forum so that the user can select the category of the post from a drop down list, rather than goto the category first and going to new topic, what I am trying to do now is when the thread is created, rather than jumping to the standard "your new thread was created here" it redirect to the category the topic was made under.
I tried using
header( "Location: category.php?id='. $topic_cat . '" );
But header was already being used elsewhere.
So I found a meta refresh that works to an extent..
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id='. $topic_cat .'>";
But it redirects to "category.phpid=" and outputs the following message..
The category could not be displayed, please try again later.You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 8
Is there anyway I can make the page jump to the category that is only being defined in the submit function itself? Thanks for any help.
EDIT: would using "if" functions work to define the redirect? ie. if topic_cat 2 is selected in the form redirect to category.phpid=2??
Sorry I am very new to PHP and still trying to get my head around it all :(
Here is the topic creation page in it's entirety
<?php
//create_topic.php
include 'connect.php';
if($_SESSION['signed_in'] == false)
{
//the user is not signed in
echo 'Sorry, you have to be signed in to create a topic.';
}
else
{
//the user is signed in
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
//retrieve the categories from the database for use in the dropdown
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
$result = mysql_query($sql);
if(!$result)
{
//the query failed, uh-oh :-(
echo 'Error while selecting from database. Please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
//there are no categories, so a topic can't be posted
if($_SESSION['user_level'] == 1)
{
echo 'You have not created categories yet.';
}
else
{
echo 'Before you can post a topic, you must wait for an admin to create some categories.';
}
}
else
{
echo '<form method="post" action="">';
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select><br />';
echo '<textarea name="post_content" /></textarea><br /><br />
<input type="submit" value="Create topic" />
</form>';
}
}
}
else
{
//start the transaction
$query = "BEGIN WORK;";
$result = mysql_query($query);
if(!$result)
{
//Damn! the query failed, quit
echo 'An error occured while creating your topic. Please try again later.';
}
else
{
//the form has been posted, so save it
//insert the topic into the topics table first, then we'll save the post into the posts table
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . mysql_real_escape_string($_POST['topic_cat']) . ",
" . $_SESSION['user_id'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your data. Please try again later.<br /><br />' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
//the first query worked, now start the second, posts query
//retrieve the id of the freshly created topic for usage in the posts query
$topicid = mysql_insert_id();
$sql = "INSERT INTO
posts(post_content,
post_date,
post_topic,
post_by)
VALUES
('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . $topicid . ",
" . $_SESSION['user_id'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your post. Please try again later.<br /><br />' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
$sql = "COMMIT;";
$result = mysql_query($sql);
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id=". $topic_cat ."'>";
}
}
}
}
}
; ?>
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id=" . $topic_cat . "'>";
That should work. You needed to put double quotation-marks outside the . $topic_cat . variable like so; " . $topic_cat . "

drop down menu goes back to displaying "Please Select" and fail/success message not appearing

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

PHP code to redirect if mysql field is complete

I would like to create page that if someone has already entered their data it redirect them to a page where it says 'sorry you have already made your selection'. The easiest field would be attendance1 where the value is either a 'Yes' or a 'No' so if it is either one of these values it will redirect to the page i want. Code for my page is here: http://pastebin.com/1D6PrmBv
Try this.
include('connect.inc');
if (( $rows['food'] == "yes" ) || ( $rows['food'] == "no" )) {
header('location: mypagelocation.html');
exit;
}
or you can write it this way too.
include('connect.inc');
if (in_array($rows['food'], array("yes","no"))) {
header('location: mypagelocation.html');
exit;
}
include('connect.inc');
if (isset($rows['food'])) {
header(location: mypagelocation.html');
exit;
}
else{
// $rows['food'] is not set
}
include('connect.inc');
if ( $rows['food'] == "yes" OR $rows['food'] == "no" ) {
header('location: mypagelocation.html');
}
Make sure there is no output before that.
Full Code:
<?php
session_start();
require_once("connect.inc");
if(!isset($_SESSION['username'])){
header('Location: connect.php');
exit;
}else{
$sql = "SELECT attendance1 FROM user WHERE username = '".mysql_real_escape_string($_SESSION['username'])."'";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
if(($row[0] == "Yes") || ($row[0] == "No")){
header("Location: redirect_page.html");
exit;
}
}
if(isset($_POST['submit'])){
$sql = "UPDATE user SET attendance1= '" . mysql_real_escape_string($_POST['attendance1']) . "' WHERE username = '" . mysql_real_escape_string($_SESSION['username']) . "'";
mysql_query($sql) or die("Error in SQL: " . mysql_error());
$sql = "UPDATE user SET gender= '" . mysql_real_escape_string($_POST['gender']) . "' WHERE username = '" . mysql_real_escape_string($_SESSION['username']) . "'";
mysql_query($sql) or die("Error in SQL: " . mysql_error());
header("Location: index.html", true, 303); // Look up "303: See Other"
exit;
}
?>

Categories