404 error when submitting form with empty field - php

I have a php page with several html forms. When a submit button is pressed while a text field is empty, I want an error to appear when the page refreshes, but instead I'm getting a 404 error. What's weird is I don't get a 404 if the fields are not empty.
This is the code for /books/index.php and the 404 error states The requested URL /books/index.php was not found on this server.
<?php
//Books
//Variables on refresh:
// $_POST['pgNum'] //Page number
// $_POST['id'] //If page is being updated. ID of the book being updated
// $_POST['newBook'] //If new book is added. Name of the new book
// $_GET['empty'] //If the form to add a new book was submitted with 1 or more empty fields.
//Equals 1 if book name is empty, 2 if page number is empty, and 3 if both are empty.
// $_GET['emptyPgNum'] //If an update button was pressed with no page number in the corresponding field,
//this variable will exist on the redirect
require_once 'connection.php'; //Function to connect to MySQL database
require_once 'queryFunctions.php'; //Functions for sending MySQL queries
if(isset($_GET['emptyPgNum'])) {
//Reload from submission with an empty page number field
echo '<font color="red">Missing page number</font><br>';
}
//Check if this page loaded from a successful form submission
if(isset($_POST['id'])) { //If page update was submitted
//Check for empty form field
if(empty($_POST['pgNum'])) {
//Empty page number field. Redirect with error
unset($_POST);
header('Location: index.php?emptyPgNum=3');
}
//Update the pageNumber field and redirect back to index.php
$conn = getConnection();
$update = "UPDATE Books SET pageNumber={$_POST['pgNum']}
WHERE id={$_POST['id']}";
booleanQuery($conn, $update);
mysqli_close($conn);
header('Location: index.php');
} else if(isset($_POST['newBook'])) { //If new book is being added
//Check if any form fields were submitted empty
if(empty($_POST['newBook']) && empty($_POST['pgNum'])) {
//Both fields empty
unset($_POST);
header('Location: index.php?empty=3');
} else if(empty($_POST['newBook'])) {
//Empty book name
unset($_POST);
header('Location: index.php?empty=1');
} else if(empty($_POST['pgNum'])) {
//Empty page number
unset($_POST);
header('Location: index.php?empty=2');
}
//Insert the new book into the database and redirect back to index.php
$conn = getConnection();
$update = "INSERT INTO Books (name, pageNumber) VALUES(\"{$_POST['newBook']}\", {$_POST['pgNum']});";
booleanQuery($conn, $update);
mysqli_close($conn);
header('Location: index.php');
} else {
//No POST data
//HTML to add page title
?>
<head>
<title>Books</title>
</head>
<?php
//Retrieve the list of books
$conn = getConnection();
$query = 'SELECT * FROM Books ORDER BY id;';
$result = mysqli_query($conn, $query);
if(mysqli_errno($conn)) { //Display error if query failed
echo "<br>Query error:" . mysqli_error($conn) . "<br>" . mysqli_errno($conn) . "<br>";
exit();
}
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<body OnLoad="document.form1.pgNum.focus()"> <!--Set cursor focus to the first form field-->
<?php
//For each book in the database, show it's current page number and create a form for submitting a page update
$formNumber = 1;
while($row = mysqli_fetch_array($result)) {
echo "\"{$row['name']}\" page number: {$row['pageNumber']}<br>";
echo '<form action="index.php" method="post" name="form' . $formNumber . '">';
echo 'New Page Number: <input type="text" name="pgNum">';
echo '<input type="hidden" name="id" value="' . $row['id'] . '">';
echo '<input type="submit" value="Update">';
echo '</form><br>';
$formNumber++;
}
echo "<br>";
//Check if this page loaded from an unsuccessful form submission
if(isset($_GET['empty'])) {
//$_GET['empty'] equals 1 if book name is empty, 2 if page number is empty, and 3 if both are empty.
switch($_GET['empty']) {
case 1:
echo '<font color="red">Missing book name</font><br>';
break;
case 2:
echo '<font color="red">Missing page number</font><br>';
break;
case 3:
echo '<font color="red">Empty fields</font><br>';
break;
}
}
?>
<!--Create a form for adding a new book to the database-->
<form method="post">
New Book: <input type="text" name="newBook"><br>
Page Number: <input type="text" name="pgNum">
<input type="submit" value="Add">
</form>
</body>
</html>
Edit: I used to have the full qualified http:// address in all the header lines and still had the same error. I changed them to the shortened versions during debugging.

Related

Prevent new rows from being inserted when max records reached?

I have an SQL table where I want the max numbers of records to be 8.
I have a form to capture input via PHP and I thought I had an error handler that operates by counting the number of records in the table and, through an IF statement, punts the user back with an error if there are >= 8 records:
<?php
// Connect to database
include_once 'db_connect.php';
// Check for form action and submitted fields
if (isset($_POST["submit"])) {
$artist = $_POST["artist"];
$song = $_POST["song"];
$link = $_POST["link"];
// Link to external error handling functions
require_once 'functions.php';
// Check for empty fields
if (emptyFields($artist, $song, $link) !== false) {
header("location: index.php?error=empty");
exit();
}
// Check if record already exists
if (songExists($conn, $link, $song) !== false) {
header("location: index.php?error=duplicate");
exit();
}
// Check if link is valid
if (invalidLink($link) !== false) {
header("location: index.php?error=invalidlink");
exit();
}
// Check if table records are greater than or equal to 8
$sql = "SELECT COUNT(*) AS Num FROM songs";
$result = mysqli_query($conn, $sql);
if ($dbName['Num'] >= 8) {
header("location: index.php?error=maxreached");
exit();
}
// If no errors from above, add to table
addSong($conn, $artist, $song, $link);
}
else {
header("location: index.php?error=none");
exit();
}
<?php
include_once 'db_connect.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Song Submission</title>
</head>
<body>
<form action="sb_process2.php" method="POST" autocomplete="off">
<input type="text" name="artist">
<br>
<input type="text" name="song">
<br>
<input type="text" name="link">
<br>
<button type="submit" name="submit">Submit Song</button>
</form>
<?php
if (isset($_GET["error"])) {
if ($_GET["error"] == "empty") {
echo "<p>Please enter all fields.</p>";
}
else if ($_GET["error"] == "duplicate") {
echo "<p>This song has already been submitted.</p>";
}
else if ($_GET["error"] == "invalidlink") {
echo "<p>Please enter a valid URL for the Spotify link.</p>";
}
else if ($_GET["error"] == "none") {
echo "<p>Song added!</p>";
}
}
?>
I tested for my first 3 error cases and all are operating as planned (they route back with an error "code"). However, if I try to submit an entry without any errors, I just get a blank page. I ran the code through a simple PHP syntax checker and it didn't come up with any errors.

PHP code inserts into sql db with text box inputs but not with select options (dropdowns)

Through hours of research and looking through code in questions submitted on this site, I was finally able to get the select options (dropdowns) to pull data from my database tables into the dropdown lists on my html form.
However, my issue is that when the fields on the form were inputs they inserted the new information into the database just fine. Unfortunately, now that I've implemented the dropdown lists as part of the form, none of the information from the form inserts into the database anymore. Clicking on the 'submit' button returns the response that it was successful, but when I check the table in the database, the new information is not there.
I'm sorry I haven't been able to figure this piece of functionality out by myself. I noticed my last question received negative feedback, so I'm leary to even submit this one, but I really need some help.
Will you please look through the following code and let me know what I'm missing or have coded incorrectly? I just need to know what I need to do to make the selected values from the dropdown lists insert into the 'dvd' table and 'categoryname' and 'genretype' fields, respectively.
<?php
session_start();
//include the header
include ('../main/header.php');
// Check if the form has been submitted.
if (isset($_POST['submitted'])) {
require_once ('../../../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize error array.
// Check for a first name.
if (empty($_POST['title'])) {
$errors[] = 'You forgot to enter a title.';
} else {
$title = mysqli_real_escape_string($dbc, $_POST['title']);
}
// Check for a category.
if (empty($_POST['numavail'])) {
$errors[] = 'You forgot to enter quantity purchased.';
} else {
$numavail = mysqli_real_escape_string($dbc, $_POST['numavail']);
}
// Check for a category.
if (empty($_POST['categoryname'])) {
$errors[] = 'You forgot to enter a category.';
} else {
$categoryname = mysqli_real_escape_string($dbc, $_POST['categoryname']);
}
// Check for a genre.
if (empty($_POST['genretype'])) {
$errors[] = 'You forgot to enter a genre.';
} else {
$genretype = mysqli_real_escape_string($dbc, $_POST['genretype']);
}
if (empty($errors)) { // If everything's OK.
// Add the movie to the database.
// Check for existing record.
$query = "SELECT id FROM dvd WHERE title='$title'";
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
if ($result) { // If it ran OK.
echo "<p><b>Success! The new movie has been added.</b></p>";
echo ('<p><div style="margin-top:30px;">');
echo ('<span style="float:left;">');
echo ('<FORM METHOD="LINK" ACTION="../dvd/index.php"><INPUT TYPE="submit" VALUE="Back to DVDs" STYLE="margin:0px 15px 0px 0px;"></form></span></div></p>');
echo ('<br style="clear:both;"></br>');
exit();
} else { // If it did not run OK.
$errors[] = 'The movie could not be added due to a system error. We apologize for any inconvenience.'; // Public message.
$errors[] = mysqli_error($dbc); // MySQL error message.
}
} else { // Title is already taken.
$errors[] = 'The movie title entered already exists.';
}
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} else { // Form has not been submitted.
$errors = NULL;
} // End of the main Submit conditional.
// Begin the page now.
if (!empty($errors)) { // Print any error messages.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo "$msg<br />";
}
echo '</p>';
echo '<p style="color:red; font-weight:bold;"><em>Please try again.</em></p></br>';
}
// Create the form.
?>
<h1>Add a Movie</h1>
<h2>Please complete all of the fields below:</h2>
<form action="../dvd/add.php" method="post">
<p>Title: <input type="text" name="title" size="15" maxlength="15" value="<?php echo $_POST['title']; ?>"></p>
<p>Quantity Purchased: <input type="text" name="numavail" size="15" maxlength="30" value="<?php echo $_POST['numavail']; ?>"></p>
<p>
<?php
include ('../../../mysqli_connect.php'); // Connect to the db.
$ddlquery = "SELECT categoryname FROM category ORDER BY categoryname ASC";
$ddlresult = mysqli_query($dbc, $ddlquery) or die("Bad SQL: $ddlquery");
echo 'Category: <select name="categoryname" size="1">';
while($ddlrow=mysqli_fetch_array($ddlresult, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow['categoryname']."'>" . $ddlrow['categoryname'] . "</option>";
}
echo "</select>";
?>
<p>
<?php
$ddlquery2 = "SELECT genretype FROM genre ORDER BY genretype ASC";
$ddlresult2 = mysqli_query($dbc, $ddlquery2) or die("Bad SQL: $ddlquery");
echo 'Genre: <select name="genretype" size="1">';
while($ddlrow2=mysqli_fetch_array($ddlresult2, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow2['genretype']."'>" . $ddlrow2['genretype'] . "</option>";
}
echo "</select>";
?>
<p>
<input type="submit" name="submit" value="Submit">
<input type=reset value=Reset>
<input type="hidden" name="submitted" value="TRUE"></p>
</form>
<?php
// Include footer.php
include("../../includes/footer.php");
?>
You forgot to actually run the insert into database
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
$result = mysqli_query($dbc, $query); // <---- ADD HERE
if ($result) { // If it ran OK.
....

when displaying records its duplicating on page refresh?

my code looks like this
when I refresh the page it's duplicating the last value how to avoid this problem. This is the quoa.php code! I have tried adding distinct but its working fine but there is no use problem still on there?
phpcode
<?php
/* connection inclution code will be here */
include 'connection/conn.php';
//defining the variables to the text fields
$question = $_POST['qst'];
$questionext = $_POST['qsttextarea'];
//validating the text fields , if there is no text show the msg after else
if(isset($_POST['qst']) && isset($_POST['qsttextarea']))
{
} else {
$pleasefill = "please fill all the fields";
}
//sending data to the database
$mysqlinsert = "INSERT INTO questions(qsttable,qstext) VALUES ('$question','$questionext')";
//header("Location: success.php");
if (!mysqli_query($connection,$mysqlinsert)) {
echo " record not inserted";
} else {
$submited = (" your question is submited please wait for the response");
}
//getting data from the database
if ($data = mysqli_query($connection,"select distinct * from questions")); {
}
?>
show record code
<?php
while($row=mysqli_fetch_array($data)) {
echo '
<div id="question_div"> <span class="fa fa-chevron-right" id="spantick"></span> '.''.$row['qsttable'].' <br />'.'<p id="qstext">'.$row['qstext'].' </p> </div> ' ;
}echo ' Read more ';
?>
You should perform html validation in your input fields ,in that way when you refresh the page all the fields will be empty and previous values will not be stored.
Just add 'required' keyword in your fields ,that will do.
eg.

How to remove a row from MySQL table data using html delete button in PHP

I am working on a project, for school. I currently have a product page to display an assortment of item includes image, description and price etc...
Under each product I have a delete button, when logged in as admin, which displays fine.
if (is_admin())
echo '<button>Delete item</button>'; }
I want to know how remove the row of data from MySQL table on clicking the delete button.
<?php
// Include need php scripts
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
include ("Includes/header.php");
if (!empty($_GET['cat'])) {
$category = $_GET['cat'];
$query = mysqli_query($db, "SELECT * FROM products WHERE category = '".$category."'");
} else {
$query = mysqli_query($db, "SELECT * FROM products");
}
if (!$query) {
die('Database query failed: ' . $query->error);
}
$deleted = mysql_query($db, "DELETE FROM products");
?>
<section>
<div id="productList">
<?php
$row_count = mysqli_num_rows($query);
if ($row_count == 0) {
echo '<p style="color:red">There are no images uploaded for this category</p>';
} elseif ($query) {
while($products = mysqli_fetch_array($query)){
$file = $products['image'];
$product_name = $products['product'$];
$image_id = $products['id'];
$price = $products['price'];
$desc = $products['description'];
echo '<div class="image_container">';
echo '<a href="viewProduct.php?id=' . $image_id . '"><p><img src="Images/products/'.$file.'" alt="'.$product_name.'" height="250" /></p>';
echo '' . $product_name ."</a><br>$" . $price . "<br>" . $desc;
echo '</div>';
if (is_admin()){
echo '<button>Delete item</button>';
}
}
} else {
die('There was a problem with the query: ' .$query->error);
}
mysqli_free_result($query);
?>
</div>
</section>
<?php include ("Includes/footer.php"); ?>
<!-- end snippet -->
You should post to a url with the id in the post data, then redirect back to where you were.
<?php
//html on productpage
if(isset($_GET['product_deleted'])){
if($_GET['product_deleted'] === 'true'){
echo 'The product was deleted';
}else{
echo 'The product could not be deleted';
}
}
if (is_admin()){
/**
* It's a good idea for the page that deletes to be different from the one your on, so that when you redirect back,
* they can refresh the page without getting something
* along the lines of 'refreshing with page will re-post the data'
*/
?>
<form method="POST" action="/product/delete.php">
<button>Delete item</button>
<input type="hidden" name="id" value="<?php echo $image_id; ?>" />
</form>
<?php
}
//PHP on /product/delete.php
if(is_admin() && $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['id'])){
//delete sql here
header('Location: /productpage.php?product_deleted=true'); //redirect back
}
One approach
Change the button to a a element and make the href look like this:
yourdomain.tld/products/delete/{id}
You have to echo the primary key from your mysql database at the id position. It will look like this:
yourdomain.tld/products/delete/5
Then you have to change your .htaccess in a way that all requests go to your index.php in your root project. At the index.php you can do the actually query then.
Update
Keep in mind that anyone visiting this URL can delete products with this approach. You have to make sure that only the admin can do that. The preferred method is a POST request.
You can also send the primary key parameter to your PHP script you are just showed. With this approach you don't need to edit your .htaccess. You may pass it as an URL parameter like this:
yourdomain.tld/your-script.php?delete-product={id}
In your script you can get the parameter like this:
<?php
if (isset($_GET['delete-product'])) {
// your mysql query to delete the product
} else {
// something else
}
If you want to delete the entire row of an record from your db you can do like this. So that you can pass the product id and delete the row. Just bind the id with query using bind parameters concept
$knownStmt=mysqli_prepare($conn, "DELETE FROM `YourTableName` WHERE `pdt_id` = ?;");
if( $knownStmt ) {
mysqli_stmt_bind_param($knownStmt,"d",$pdt_id);
mysqli_stmt_execute($knownStmt);
mysqli_stmt_close($knownStmt);
}

MySQL database is updated with empty value when updating using PHP

I am new in php, i tried this coding i select a value in my drop down list i want a corresponding value to be updated, i have list of user name in my database and a ID for them, i am displaying the user name and when i want to update i written a sql query to find the member id and update to database but it's inserting a null value. Here is my code.
Dropdown list code
<?
session_start();
if(!isset($_SESSION[''])){
header("location:");
}
?>
<?php include('dbconnect.php'); ?>
<?php
$ed=$_GET['ed'];
$query=mysql_query("select * from table1 where id='$ed'");
$query2= "select * from table2";
$row=mysql_fetch_assoc($query);
if($_POST['Submit'])
{
$mem= $_POST['memid'];
$memname =mysql_query("select memid from table2 where name='$mem'");
$memname1= mysql_fetch_assoc($memname);
$tot_count = mysql_fetch_assoc($ro_count);
$date=date("d-m-Y");
$status="Active";
$onamo=mysql_real_escape_string($_POST['onamo']);
$heid = mysql_real_escape_string($_POST['memname1']);
if($_POST['heid']=='')
{
$namo1="*Required";
$ok=1;
}
if($_POST['onamo']=='')
{
$onamo1="*Required";
$ok=1;
}
$insert=mysql_query("update table1 set oname='$onamo', heid='$heid' where id='$ed'") or die('error');
if($insert)
{
header("Location");
}
}
?>
<body>
<div id="main_container"><br />
<div class="main_content">
<div class="center_content">
<div class="right_content">
<div class="form">
<form action="" method="post" name="fomo" enctype="multipart/form-data" onsubmit="return fall();" class="niceform">
<h1 align="center">Edit Referal Partner </h1>
<?
if($_GET['val']==1) { echo "<h1 class='FeatureBlockHeader' >Member Added Successfully</h1>"; } ?>
<fieldset>
<dl><dt><label for="Owner Name">Referal Partner Name</label></dt><dd><input name="onamo" type="text" size="53" id="onamo" value="<?=$row['oname']?>"/><b style="color:#CA0000"><?=$onamo1?></b></dd></dl>
<dl><dt><label for="">Health Executives</label>
<?php $result1 = mysql_query($query2);
echo'<select name="memid" >';
while($row = mysql_fetch_assoc( $result1 )) {
echo '<option value="'.$row['name'].'">' . $row['name'] . '</option>';
}
echo '</select>'; ?>
</b></dd></dt>
<dl><dt><label for="submit"></label></dt><dd> <input type="submit" name="Submit" value="Submit"></dd></dl></fieldset>
</table>
</form>
'
My database is updated with empty string, if i directly pass the dropdown value Name it's updating fine. But i want to update the corresponding memberid to my table. Please help me.
Stage 1:
You don't do anything if the field is blank. (Plus you have your logic wrong with $ok).
Suggested code would be:
$ok = 1; // assume ok unless we have an error
if($_POST['heid']=='')
{
$namo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if($_POST['onamo']=='')
{
$onamo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if ($ok)
{
// Do your update
$insert = mysql_query("update table1 set oname='$onamo', heid='$heid' where id='$ed'") or die('error');
if($insert)
{
header('location: ???');
exit(); // ALWAYS exit after a header redirect, otherwise the rest of the code will continue to work, then the redirect happens!
}
$ok = 0;
$error = 'Failed to update database'
}
// If you get here, you have an error condition.
** Stage 2:**
You should check for isset($_POST['onamo']) before getting the variable. Otherwise it would throw a warning. This will probably give you the error. You have a discrepancy between 'heid' and 'memname1'! :)
$ok = 1; // assume ok unless we have an error
if(!isset($_POST['heid']) || $_POST['heid']=='') // Or is it $_POST['memname1']?
{
$namo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if(!isset($_POST['onamo']) || $_POST['onamo']=='')
{
$onamo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if ($ok)
{
$onamo=mysql_real_escape_string($_POST['onamo']);
$heid = mysql_real_escape_string($_POST['memname1']); // Or is it $_POST['heid'] ??
// Do your update
$insert = mysql_query("update table1 set oname='$onamo', heid='$heid' where id='$ed'") or die('error');
if($insert)
{
header('location: ???');
exit(); // ALWAYS exit after a header redirect, otherwise the rest of the code will continue to work, then the redirect happens!
}
$ok = 0;
$error = 'Failed to update database'
}
// If you get here, you have an error condition.

Categories