html form post is not sending variable data - php

After clicking "delete" (submit): I can tell that it processes the form because I get the error "You forgot to select a vendor to delete.".
The form itself is generated using PHP. When I check the HTML output, I see that the values are there. But when it gets to POST, nothing carries over. I'm testing and using a local host, so other than the existing action link, I'm not sure what else I can modify.
I have the exact same code in another delete form and it works fine. I literally copied the other form to create this one and just changed the SQL/Variable names.
PHP Code:
#delete vendor
require('includes/mysqli_connect.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); //array to collect errors
//check to ensure fields are filled out
if (!empty($_POST['vendor'])) {
$vendor = trim($_POST['vendor']);
}
else {
$errors[] = "<p>You forgot to select a vendor to delete</p>";
}
if (empty($errors)) {
//insert information into appt table
$query = "UPDATE vendors_t SET active = 0 WHERE vendorID = $vendor;";
$result = mysqli_query($dbc, $query);
if($result){
echo '<div class="alert alert-success" role="alert">';
echo '<h2>Thank you!</h2>';
echo '<p> Your request to delete vendorID ' . $customerID . 'has been completed </p></div>';
} else {
echo "Error updating record: " . mysqli_error($dbc);
}
} else{
echo '<div class="alert alert-danger" role="alert"><br>';
echo '<h2>Errors Detected</h2>';
echo '<p>The following errors occured:<br/>';
foreach ($errors as $msg) {
echo "$msg<br/>\n";
}
echo '</p><p>Please try again. </p></div>';
}
}
HTML Code
<div class="container standout" >
<div class="col-lg-12">
<h2>Delete a vendor</h2>
<p> Please select a vendor to delete.</p>
</div>
<div class="row">
<form action="index.php?pagelet=deletevendor" method="post">
<div class="form-group col-md-4">
<label for="vendor">Vendors</label>
<select name="vendor" class="form-control">
<option name="vendor" selected disabled>Choose here</option>
<?php
$query = "SELECT vendorID, contactFname, contactLname, businessName FROM vendors_T WHERE active = 1;";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<option name="vendor" value="'.$row['vendorID'].'">'
.$row['vendorID'].' '.$row['businessName']
.' '.$row['contactFname'].' '.$row['contactLname']
.'</option>';
}?>
</select>
<br>
<br>
<input class="btn btn-primary" id="submit" type="submit" value="Delete">
</div>
</div>
</form>
</div>

Your option names should be the value of the vendor ID (I presume) and certainly not "vendor".

removing name="vendor" from options & removing selected both work.
After removing name="vendor" - I added selected back and it still works.
Thank you!!

Related

How to submit just one button from a set of buttons that are displayed using a php while-loop

I am coding a website for an online university portal where I have a programs/courses page in which I am displaying the programs/courses on the page using data from the database in a PHP while-loop I have the enroll buttons also being displayed in that same while loop. but I'm having a bit of difficulty submitting the enroll buttons as when I click one of them all of them get submitted.
can anyone please let me know what I'm doing wrong here or if I have to use any javascript in this case!
<?php
session_start();
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, 'htdatabase');
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$id = $_SESSION['userID'];
$sql = "SELECT * FROM programs";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$i = '';
$progID = $row["progID"];
$name = $row["progName"];
$halfTime = $row["halfTDuration"];
$fullTime = $row["fullTDuration"];
$fee = $row["fee"];
$descrip = $row["description"];
$stringname = strval($name);
$spaceRemoved = str_replace(' ', '', $stringname);
?>
<div class="card-header" id="headingOne">
<h5 class="mb-0">
<?php echo "<button class='btn btn-link' type='button' data-toggle='collapse' data-target='#$spaceRemoved' aria-expanded='false' aria-controls='$spaceRemoved'> $name </button>"; ?>
</h5>
</div>
<?php echo "<div id='$spaceRemoved' class='collapse' aria-labelledby='headingOne' data-parent='#accordionExample'>"; ?>
<div>
<div class="ccard-body col-md-9">
<h6><?php echo $descrip; ?></h6>
<hr>
<h5>Duration:</h5>
<h6>Full time: <?php echo $fullTime; ?></h6>
<h6>Half time: <?php echo $halfTime; echo $i; ?></h6>
<hr>
<h5 style="display: inline-block;">Estimated fees: $</h5><h5 style="display: inline-block;"><?php echo $fee ?></h5>
</div>
<form action="programs.php" method="post">
<div id="enroll" class="col-md-3">
<?php
$sql1 = "SELECT * FROM userprograms WHERE userID = '$id' AND progID = '$progID'";
$result1 = $con->query($sql1);
if ($result1->num_rows > 0) {
echo '<div id="enrolled" name="enrolled">ENROLLED</div>';
} else {
if (isset($_POST["enroll"])) {
$enrollqry = "insert into userprograms (userID, progID) values ('$id' , '$progID')";
mysqli_query($con, $enrollqry);
}
echo "<button name='enroll'type='submit'>ENROLL</button>";
}
?>
</div>
</form>
</div>
</div>
<?php
}
} ?>
You can specify a value for the button. like
<button name='enroll' value="<?php echo $program_id?>" type='submit'>ENROLL</button>
Then when checking for $_POST['enroll'] check the value and also validate it before entry to db.
After clicking the submit button a browser will send a POST request to programs.php with a form data, that includes values of input & button tags.
<input type="submit" name="course1" value="42">Subscribe</input>
<input type="text" name="first_name" placeholder="Your name"/>
Will send
course1=42
first_name=...
So you should either give a unique name to each submit button to be able to distinguish them on the server-side, or set up distinct values, as #mohamed-jailam mentioned above.

Undefined array key, cant understand why the php file seems to not get the value in the html form

This is just for a school project and it feels like such a simple problem but every time i google what seems to be the problem i just cant understand most of the answers
<form action="bookResults.php" method="get">
<h4>Book Search</h4>
<label for="searchType">Search Type:</label>
<select name="searchType" id="searchType">
<option value="title">Title</option>
<option value="author">Author</option>
<option value="isbn">ISBN</option>
</select><br>
<label for="searchTerm">Search Term:</label>
<input type="text" name="searchTerm"><br>
<a class="btn btn-primary" href="bookResults.php" role="button">Submit</a>
</form>
this is the form in html
<?php
if (!isset($_GET['searchType'])) {
$searchType = $_GET['searchType'];
if (!isset($_GET['searchTerm'])) {
$searchTerm = $_GET['searchTerm'];
echo $searchType;
echo $searchTerm;
if(!$searchType || $searchTerm){
echo 'You have not entered search details. Please go back and try again';
}else{
$mysqli = new mysqli('127.0.0.1:3306','zero','1234','mp7');
if ($searchType == 'title') {
$query = "select * from book where title like '%".$searchTerm."%'";
$result = $mysqli->query($query);
$resultCount = $result->num_rows;
echo "<p>Result for ".$searchType." : ".$searchTerm." </p>";
echo "<p>Number of books found: ".$resultCount."</p>";
for($ctr = 0;$ctr<$resultCount;$ctr++){
$row = $result -> fetch_assoc();
echo "<div class='card col-4'>";
echo " <div class='card-body'>";
echo " <h6>".$row['title']."</h6>";
echo " <p>By ".$row['author_name']."<br/>";
echo " ".$row['isbn']."</p>";
echo " </div>";
echo "</div>";
}
}
and this is my incomplete php code, the goal is to let the user choose with a dropdown menu between 3 categories in my book table in my database. its either they search by Author, title or isbn. But i cant even get to that part without getting this "undefined array key" error in the first few lines
EDIT: The next project i was supposed to work on involved prepared statements, the school just wanted us to use manual insertions i guess
You don't use an anchor to submit a form. You have to use a submit button. So change
<a class="btn btn-primary" href="bookResults.php" role="button">Submit</a>
to
<button class="btn btn-primary" type="submit" role="button">Submit</button>
When you use the anchor, none of the form fields are added to the URL.
You also have some problems in your PHP logic.
You can combine the tests for whether the parameters are set and properly filled in by using !empty(). You can test both parameters at once, rather than using nested if statements.
Your code is also wide open to SQL injection. You should use a prepared statement with parameters rather than substituting the variable into the SQL.
<?php
if (!empty($_GET['searchType']) && !empty($_GET['searchTerm'])) {
$searchType = $_GET['searchType'];
$searchTerm = $_GET['searchTerm'];
echo $searchType;
echo $searchTerm;
$mysqli = new mysqli('127.0.0.1:3306','zero','1234','mp7');
if ($searchType == 'title') {
$query = "select * from book where title like CONCAT('%', ?, '%')";
$statement = $mysqli->prepare($query);
$statement->bind_param("s", $searchTerm);
$statement->execute();
$result = $statement->get_result();
$resultCount = $result->num_rows;
echo "<p>Result for ".$searchType." : ".$searchTerm." </p>";
echo "<p>Number of books found: ".$resultCount."</p>";
for($ctr = 0;$ctr<$resultCount;$ctr++){
$row = $result -> fetch_assoc();
echo "<div class='card col-4'>";
echo " <div class='card-body'>";
echo " <h6>".$row['title']."</h6>";
echo " <p>By ".$row['author_name']."<br/>";
echo " ".$row['isbn']."</p>";
echo " </div>";
echo "</div>";
}
}
} else {
echo 'You have not entered search details. Please go back and try again';
}

Is my statement not updating because of the way I have it layed out?

This "page" is part of many that are all linked together using includes, but because I can't make it work I'm going straight to the url that relates to this exact page, and I still can't make it work, or figure out why.
What is supposed to happen, is the query checks if that stock is in the db, if it is, echo the values of the row, and if a submit button is pressed update the db based on the input values. If it's not in, echo the blank form, and if a submit button gets pressed insert into the db. I can't get either update or insert to work.
I'm going to post the entire page (minus the mysql connect,) so hopefully someone can spot an error.
<?php
$status = 'Active';
$stock = (isset($_GET['stock'])) ? $_GET['stock'] : '';
$cat = (isset($_GET['cat'])) ? $_GET['cat'] : '';
include ('../helper_content/title_data.php');
/* WHAT CATEGORY DO WE WANT? */
if($cat == "Sales") {
$table = "Titles";
if($stock) {$where = "stock = $stock";}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$status = $status;
$title_status = mysqli_real_escape_string($conn,$_POST['title_status']);
$title_number = mysqli_real_escape_string($conn,$_POST['title_number']);
$title_location = mysqli_real_escape_string($conn,$_POST['title_location']);
$title_owners = mysqli_real_escape_string($conn,$_POST['title_owners']);
$stock = $_GET['stock'];
}
}
/* Begin Main Query */
$sql5 = "SELECT * FROM `$table` WHERE $where";
$result5 = $conn->query($sql5);
if ($result5->num_rows > 0) {
// Stock exists, so submit will Update dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($update = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$update->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$update->execute();
};
if ($update->execute == TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating: " . $update->error;
}
}
// Display the HTML results
while($row5 = $result5->fetch_assoc()) {
echo "Found In Database";
// Title Number
$title_number = 'value="'.$row5['title_number'].'"';
$TitleStatus = $row5['title_status'];
$TitleLocation = $row5['title_location'];
$Owners = $row5['owners'];
}
} else {
// No Query Results Found
echo "Not Found In Database";
// Insert into dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($add = $conn->prepare("INSERT INTO `Titles` status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$add->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$add->execute();
};
if ($add->execute == TRUE) {
echo "Record added into database";
} else {
echo "Error adding: " . $add->error;
}
}
/* End Main Query */
}
// Title Status
foreach($title_statuses as $title_status){
$selected = ($TitleStatus == $title_status) ? ' selected="selected"' : '';
$Title_status .= '<option value="'.$title_status.'"'.$selected.'>'.$title_status.'</option>';
}
// Title Location
foreach($title_locations as $title_location){
$selected = ($TitleLocation == $title_location) ? ' selected="selected"' : '';
$Title_location .= '<option value="'.$title_location.'"'.$selected.'>'.$title_location.'</option>';
}
// Prior Owners
foreach($prior_owners as $owners){
$selected = ($Owners == $owners) ? ' selected="selected"' : '';
$Owners_drop .= '<option value="'.$owners.'"'.$selected.'>'.$owners.'</option>';
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>?stock=<?php echo $stock; ?>">
<section class="title">
<h3>Title Info - Stock #:<?php echo $stock; ?></h3>
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" <?php echo $title_number; ?>>
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php echo $Title_status; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<?php echo $Title_location; ?>
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<?php echo $Owners_drop; ?>
</select> <a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=<?php echo $vin; ?>"><i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i></a>
</p>
</section>
<input type="submit" id="Submit" value="Submit">
</form>
I would start by organizing your code a little differently. You have one of two things that can be true: either the form was submitted (a POST request), or the page was requested via URL (a GET request). So, start with this:
<?php
# Data for dropdowns
include ('../helper_content/title_data.php');
$error = array();
$status = "Active";
$title_number = "";
$title_status = "";
$title_location = "";
$title_owners = "";
$vin = "";
# Was the form submitted via POST?
if(isset($_POST['Submit']))
{
# Yes
# Is this a new stock item?
if(empty($_POST['stock']))
{
# Yes - insert
/*
... get your variables from the $_POST array
*/
$title_number = filter_var($_POST['title_number'], FILTER_SANITIZE_STRING);
# ... repeat for other variables
if ($stmt = $conn->prepare("INSERT INTO `Titles` (`status`,`title_status`,`title_number`,`title_location`,`title_owners`) VALUES (?,?,?,?,?)"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?inserted=true');
exit();
}
else
{
$error[] = "Error adding: " . $stmt->error;
$stmt->close();
}
}
}
else
{
# No - update
$stock = $_POST['stock'];
/*
... get your variables from the $_POST array
*/
if ($stmt = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?updated=true');
exit();
}
else {
$error[] = "Error updating: " . $stmt->error;
$stmt->close();
}
}
}
}
else
{
# No - assume a GET
$status = 'Active';
$stock = $_GET['stock'];
$cat = $_GET['cat'];
if(isset($_GET['updated']))
{
$message = "Record updated";
}
else if(isset($_GET['inserted']))
{
$message = "Record added into database";
}
if($stock != "")
{
# Load the item?
$query = "SELECT * FROM `Sales` WHERE stock=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $stock);
if($stmt->execute())
{
$result = $stmt->get_result();
if($result)
{
$row = $result->fetch_assoc();
$title_number = $row['title_number'];
$title_status = $row['title_status'];
$title_location = $row['title_location'];
}
}
$stmt->close();
}
}
?>
<?php if(isset($message)) : ?>
<div class="alert alert-success">
<?= $message ?>
</div>
<?php endif; ?>
<?php if(isset($error)) : ?>
<div class="alert alert-danger">
<ul>
<?php foreach($error as $err): ?>
<li><?= $err ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<section class="title">
<h3>Title Info - Stock #:<?= $stock; ?></h3>
<input type="hidden" name="stock" value="<?= $stock; ?>" />
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" value="<?= $title_number; ?>" />
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php foreach($title_statuses as $option): ?>
<option <?= $option == $title_status) ? 'selected="selected"' : '' ?>><?= $option ?></li>
<?php endforeach; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
<a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=$vin">
<i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i>
</a>
</p>
</section>
<input type="submit" id="Submit" value="Submit" />
</form>
Here's a partial re-implementation of your page. I'm starting with the assumption that a stock number was part of the requesting URL, and looking that value up. I (for the moment) am ignoring loading the dropdown values in favor of getting a basic lookup to work.
You'll also notice I've switched to using shorttags in your markup - this is generally a more concise method of templating than sprinkling echos all over the place.
I've added a partial implementation of some save logic. You'll also notice that I added a hidden input to your form - you don't want to rely on a query string value when posting a form.
The code stores some simple error messages in an array, which gets echoed out if the insert or update fails. If successful, we redirect back to the same page with a simple flag variable, which we read on that request to know if we need to display an informational message. This is known as POST-REDIRECT-GET, and prevents users from accidentally (or purposefully) resubmitting the same form data over and over.

Delete li entry in database with PHP

I am working on a website where the user can enter the money he owes a friend. On one page the user can see all the entrys he made so far and should be able to delete them aswell. All entrys are inserted in a DB. For this overview page I use following structure:
<ul class="list-group">
<?php
$isEmpty = true;
while ($data = mysql_fetch_array($res)) {
if ($data['isDebt'] == 0) {
$isEmpty = false; ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<li class="list-group-item" name="Debt_ID" value="<?php echo $data['Debt_ID'] ?>"><span class="badge"><?php echo $data['value']; ?></span><?php echo $data['name']; ?>
<button name="delete" type="submit" id="delete" class="btn btn-xs btn-danger pull-right">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>
</li>
</form>
<?php }
}
if ($isEmpty) { ?>
<li class="list-group-item">No debt!</li>
<?php
} ?>
</ul>
One debt entry has the following values:
Debt_ID (numeric)
Name (like "pizza from jack")
Value (the price. for example "10")
The button for each li element should delete the entry in the DB via Debt_ID. I've used the following SQL statement so far:
DELETE FROM Debt WHERE Debt_ID='$debt_ID';
In PHP it looked like this:
if (isset($_GET['delete'])) {
$debt_ID = trim($_POST['Debt_ID']);
$res = mysql_query("DELETE FROM Debt WHERE Debt_ID='$debt_ID';");
if ($res) {
$errTyp = "success";
$errMSG = "Successfully deleted";
} else {
$errTyp = "danger";
$errMSG = "Error occured";
}
}
My problem right now is that I am not able to get the Debt_ID which I've entered with PHP in the li element. Does anyone know a better approach or what I am doing wrong?
I am developping with Cloud9 so I could invite someone if interested.
When you load all the debts, you can do that with a select statement and loop through the result set. In the loop you can put the id in hidden inputs in each li element:
$sql = "SELECT debt_id, name, value FROM debts WHERE user_id = " . $user_id;
$result = $conn -> query($sql);
if ($result -> num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<li>
<span>' . $row["name"] . '</span>
<span>' . $row["value"] . '</span>
<input type="hidden" value="' . $row['debt_id'] . ' name="id-to-delete">
</li>';
}
} else {
echo "no results";
}
The delete.php file should contain:
<?php
if (isset($_POST['id-to-delete'])) {
$idToDelete = $_POST['id-to-delete'];
// sql to delete a record
$sql = 'DELETE FROM debts WHERE debt_id=' . $idToDelete;
if ($conn->query($sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
?>
After the form element simply add
<input type="hidden" name="Debt_ID" value="<?php echo $data['Debt_ID'] ?>">
Then remove the same information from the li element.
When submitting a form, input elements with a name attribute are what gets passed along to the next page.

POST and GET at the same time

hello everyone sorry but am just beginner in php , mysql ... i was developing question and answer website which i have page for all Question (Q.php) and page for displaying a specific question (QR.php) and get information according to data sent from Q.php via url ($_GET['start'] i also have page to confirm that the answer is already submitted .... but i got error when entering the id from get method and the message from post method ... any answer will be appreciated
Q.php
<?php
include("pagination.php");
if(isset($res))
{
while($result = mysql_fetch_assoc($res))
{
echo '<div class="shop-item">' ;
echo ' <div class="price">' ;
echo $result['Inquirer'] ;
echo ' </div>' ;
echo ' <div class="price">' ;
echo $result['question'] ;
echo ' </div>' ;
echo ' <div class="actions"> ';
echo '<input type="button" class="btn btn-large " value="More Info" onclick="window.location=\'QR.php?start=' . urlencode($result['id']) . ' \';" />';
echo '</div> ';
echo ' </div> ';
}
}
?>
QR.php
<form action="QRR.php" method="POST">
<div class="blog-post blog-single-post">
<div class="single-post-title">
<h2>Post Your Answer</h2>
</div>
<div align="Right">
<textarea class="form-control" rows="4" name ="answer" id="Test">
</textarea>
<br>
<div class="actions">
<?php echo '<input type="button" class="btn btn-large " value="Post Answer" onclick="window.location=\'QRR.php?start=' . urlencode($_GET['start']) . ' \';" />'; ?>
</div>
</div>
</div>
</form>
QRR.php
<?php
// variables
$answer=$_REQUEST['answer'];
require ("coonection.php");
$FURL = $_REQUEST['hi'];
//query
$query = "INSERT INTO `answers`(`answer_id`, `question_id`, `answer`, `answerer`, `rate`, `dnt`) VALUES ('','$FURL','$answer','ahmed','',CURRENT_TIMESTAMP)";
$data=mysql_query($query) or die(mysql_error());
if($data)
{
echo "Your Questions Has Been Successfully Added ";
}
?>
if i removed passing hi from QR to QRR answer stored //$answer
if i removed storing answer from the text area the id from url stroed //$FURL
This isnt the most beautiful code, as i just copied yours and made a few modifications.. but this form will submit back to the same page, and the php will run and insert ONLY if the form is submitted.
if(isset($_POST['answer'])) says "if the variable _POST answer is set, run the php code and insert.. if it is not set, do nothing.
You will notice the form action is left blank, you can set it to the page name yo are on.. as the form will send the variables to the same page. This is a good way of doing it because if there are errors, you can prepopulate the input or textareas with the code they just typed in.
<?php
// variables
if(isset($_POST['answer'])){
$answer=$_POST['answer'];
require ("coonection.php");
$FURL = $_POST['hi']; // there is no input name 'hi' set in your form. so this code will fail due to that.
//query
$query = "INSERT INTO `answers`(`question_id`, `answer`, `answerer`, `rate`, `dnt`) VALUES ('$FURL','$answer','ahmed','',CURRENT_TIMESTAMP)";
$data=mysql_query($query) or die(mysql_error());
if($data){
echo "Your Questions Has Been Successfully Added ";
}
}
?>
`
you will see i removed your answer_id. if you use this code, make sure that field is set to primary auto increment in your database.
<form action="" method="POST">
<div class="blog-post blog-single-post">
<div class="single-post-title">
<h2>Post Your Answer</h2>
</div>
<div align="Right">
<textarea class="form-control" rows="4" name="answer" id="Test"></textarea>
<br>
<div class="actions">
<button type="submit" class="btn btn-large " value="Post Answer">Post Answer</button>
</div>
</div>
</div>
</form>
NOTE: both of these snippets will go in the same page.

Categories