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.
Related
I have a form which updates information inside of a DB, everything works perfectly as it should....... except for some reason the header does not work for me. I am using the header redirect in a lot of other scripts within the same site; it is just this one script that the header redirect does not work. I know that the if statement the header is inside of is called because the echo right below the header is displayed on the page, its just kind of ignoring the header line. If you have any suggestions that would be very helpful.
The code below has been minimized so its not to long for everyone to read but if it is still a problem ill clean it up even more
the form
<form class="editUser" action="uploadEmployee.php" method="post" enctype="multipart/form-data" />
<input name="editUserFirstName" id="editUserFirstName" type="text" placeholder="Enter The User's First Name" />
<label>Employee's Coverage</label>
<input type="file" name="file_array[]" placeholder="Add The Employees Coverage" />
<input name="addUserSubmit" type="submit" value="Submit" />
</form>
The uploading scripts
<?php
include("includes/connect.inc.php");
if(isset($_FILES['file_array'])){
$day = date('d');
$month = date('m');
$dateObj = DateTime::createFromFormat('!m', $month);
$monthName = $dateObj->format('F'); // March
$year = date('Y');
$date = $monthName . ", " . $day . ", " . $year;
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
$payCheque = $name_array[0];
$T4 = $name_array[1];
$coverage = $name_array[2];
$selectedId = $_POST['editId'];
$name = $_POST['editUserFirstName'];
if($_POST['editUserPermission']){
$permission = "1";
}else{
$permission = "0";
}
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
$title = "This Is A Test Title";
$icon = "0";
if($i == 0){
$icon = "1";
$title = "You Have Received A New Pay Cheque";
$comment = "Hello " . $name . ", click view document to view and download your pay cheque for " . $date . ". Your pay cheque will be a PDF file. Thank you.";
}
$sql = "INSERT INTO securedFiles (title, date, PDF, comment, idOfUser, icon)
VALUES ('$title', '$date', '$name_array[$i]', '$comment', '$documentId', '$icon')";
if ($connect->query($sql) === TRUE) {
//header("Location: hub.php");
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
echo $payCheque ." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
$sql = "UPDATE dealerEmployees SET firstName = '$_POST[editUserFirstName]', lastName = '$_POST[editUserLastName]', password = '$_POST[editUserPW]', permission = '$permission', address = '$_POST[editUserAddress]', email = '$_POST[editUserEmail]', phone = '$_POST[editUserPhone]' WHERE id = $selectedId";
if ($connect->query($sql) === TRUE) {
header('Location: hub.php');
echo "Success";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
}
//$connect->close();
?>
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
And in your case, you are using echo before header()
So you can use a redirect method(that i use in all my projects, no problems ever)
<?php
if ($connect->query($sql) === TRUE) {
echo "<script> parent.self.location = \"hub.php\";</script>";
echo "Success";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
?>
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 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
Updated with suggestion by others but still seem to be stuck.
I'm using this php code here to display info from my database using the ID. I created a link on my main page that looks like this.
<h1><?php echo $row_getDisplay['title']; ?></a></h1>
I have so when they click on the title of the article that it takes them to my php fiel which I named fetch.php and the code below is what is in there. I have built this around someone else's work. For some reason I can't get passed the first "else" statement. so I keep getting "you must select a valid location" I'm fairly new to php so I don't really understand why the code is failing.
<?php require_once('Connections/XXXXXX.php'); ?>
<?php
if (isset($_GET['id']) == false) // check if id has been set
{
echo "You must select a location"; // if not, display this error
exit;
} else {
$id = (int) $_GET['id'];
if (is_numeric($id) == false)
**{
echo "You must select a valid location.";
} else {**
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE post_id ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
Any help is appreciated. If you are able to find a better solution for me that would be great.
You shouldnt use $HTTP_GET_VARS its deprecated and unless its turned on it wont be populated. use $_GET instead.
if (isset($_GET['id']) == false)
Use $_GET for your if statement:
if (isset($_GET['id']) == false)
Also, you need to convert your $_GET value to an integer, because it is currently a string.
Right after that if statement above, in the else, put this:
$id = (int) $_GET['id'];
That way your is_numeric() will work properly.
Try this;
<?php
require_once('Connections/XXXXXX.php');
if (isset($_GET['id'])) // check if id has been set
{
$id = $_GET['id'];
if (is_numeric($id) == false)
{
echo "You must select a valid location.";
} else {
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE locationid = 'news.post_id' ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
else{
echo "You must select a location"; // if not, display this error
exit;
}
?>
Also, I need a clarification about news.post_id, from where are you grabbing this?
I have code to retrieve data from a database into a form but it doesnt seem to be working. The code below is my attempt but it doesnt work. Currently, when I click the submit button 'retrieve rose' it does nothing...
//if we have no errors, do the SQL
if (!$errors) {
$latin_name = $_POST['latin_name'];
$stmt = $conn2->prepare("SELECT common_name, variety_name, colour, season_of_interest, hardiness, situation, soil_type,
price, stock_level, fragrance, ultimate_height FROM rosename WHERE latin_name = ?");
$stmt->bind_param('ssssssssdiss', $latin_name);
if ($result = $stmt->get_result()) {
/* fetch associative array */
echo "<form><input type='text' value='" . $row["common_name"] . "' name='latin_name' />";
echo "<input type='text' value='" . $row["variety_name"] . "' name='soil_type' /></form>";
} // i no I need to add more here...
exit;
}
//put out the footer and then stop the rest of the script from running, so we don't display the rest of the form (this is after the form has been submitted)
require_once('footer.php');
exit;
}
//if we do have errors, show the error message
else {
echo "<p>".$error_msg."</p>";
}}
?>
And here is my form:
<h1>Update Rose Item</h1>
<ul class='register'>
<li>
<form action="updaterose.php" id="updaterose" method="post">
<fieldset id="register">
<label>Latin Name:<span class="small">Enter a Latin Name</span></label><input name='latin_name' id='latin_name' type='text' value="<?=(isset($_POST['latin_name'])? $_POST['latin_name']:"");?>" />
<input type="submit" value="Retrieve Rose" name='retrieverose' /></br></br></br>
</form>
Code requested by mariogl
//connect to database
$conn2 = DB2();
require_once('header_admin.php');
if (isset($_POST['updaterose']))
{
//detect if we have errors or not
$errors = false;
$error_msg = "Error, please try again";
Your problem is the first condition, you're asking for a variable named "updaterose", that doesn't exist. Try this:
if (isset($_POST['retrieverose']))
{
//detect if we have errors or not
$errors = false;
$error_msg = "Error, please try again";
//if we have no errors, do the SQL
if (!$errors) {
$latin_name = $_POST['latin_name'];
$stmt = $conn2->prepare("SELECT common_name, variety_name, colour, season_of_interest, hardiness, situation, soil_type, price, stock_level, fragrance, ultimate_height FROM rosename WHERE latin_name = ?");
$stmt->bind_param('s', $latin_name);
$stmt->execute();
if ($result = $stmt->get_result()) {
/* fetch associative array */
echo "<form><input type='text' value='" . $result["common_name"] . "' name='common_name' />";
echo "<input type='text' value='" . $result["variety_name"] . "' name='variety_name' /></form>";
// i no I need to add more here..
exit;
}
//put out the footer and then stop the rest of the script from running, so we don't display the rest of the form (this is after the form has been submitted)
require_once('footer.php');
exit;
}
//if we do have errors, show the error message
else {
echo "<p>".$error_msg."</p>";
}}
}
Corrections on brackets and bind_param().