PHP checklist get ID and value and store it - php

So I have a form to add a new item to database with a checkbox as follows
So my difficulty is the checkbox. I can easily enough create the array for all items checked but I need an ID for them along with it. I've tried to think of many ways and searched a lot but I just can't think of a way to get the ID in a way that is then useable to me along with the name of the feature (checklist). Since I have to get each feature item and add it to the table houses_has_features.
<?php
$title = 'Add a new house';
require_once 'header.php';
require_once 'nav.php';
require_once 'mysqli-con.php';
$conn = new MYSQLI($hn, $un, $pw, $db);
// If house name and type is set then add them into the database
if( !empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
$house_name = $conn->real_escape_string($_POST['h_name']);
$house_type = $conn->real_escape_string($_POST['h_type']);
//show names added
echo '<b>House name: </b>'.$house_name . '<br><b> House type:</b> ' . $house_type;
$query = "INSERT INTO `house_names` (`id`, `name`) VALUES (NULL, '$house_name')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
global $house_name_id;
$house_name_id = $conn->insert_id;
$query = "INSERT INTO `house_types` VALUES ('$house_name_id', '$house_type')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
} else {
global $house_name_id;
$house_name_id= NULL;
}
//Start container for page content
echo '<div class="container">';
//Display an error message if house name is filled in but not house type
if ( !empty($_POST['h_name']) && empty($_POST['h_type']) || empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
echo "<p class='error-text'>* Please fill in both the house name and house type *</p>";
}
$query_feat = $conn->query('SELECT * FROM features');
$rows = $query_feat->num_rows;
$features_list = $_POST['check_list'];
$feature_id = $_POST['feature_id'];
//display checked boxes.
if(isset($_POST['check_list'])) {
for ($i=0; $i<sizeof($features_list); $i++){
//echo '<br>House name id:' . $house_name_id . '<br> $_POST[] = ' . "$features_list[]";
print_r($features_list); echo '<br>';
print_r($feature_id);
}
}
// Add house form
echo <<<_END
<h1>Add a house</h1>
</div>
<div class="container">
<form action="add.php" method="post">
<p>House Name: <input type="text" name="h_name"></p>
<p>House type: <input type="text" name="h_type"></p>
<b>features:</b>
<ul class="list-group">
_END;
for ($c = 0 ; $c < $rows ; ++$c){
$query_feat->data_seek($c);
$feat = $query_feat->fetch_array(MYSQLI_NUM);
echo '<li><input type="checkbox" name="check_list[]" value="' .$feat[1]. '">'.$feat[1].'</li>';
}
echo <<<_END
<ul>
<input class="btn-primary" type="submit" value="Submit">
</form>
</div>
_END;
require_once 'footer.php';
I'm really lost on this one any help would be greatly appreciated :)

change your value of checkbox to id or anything you want.
<li><input type="checkbox" name="check_list[]" value="' .$feat[0]. '">'.$feat[1].'</li>
$feat[1] => $feat[0] or else

Related

how to update form data with submit button in a while loop

I am trying to figure out mysqli (I am just a starting scripter). I created the following script to grab 3 different values from my database. And it prints it on the screen in different textareas and input fields.
What I want to be able to do is when I press the update button that it'll update the records in the database for the form where the button is attached to.
Can anyone give me some tips on how to achieve something like that?
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$standaardtekstlabel = $mysqli->query("SELECT standaardtekst_label FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$standaardtekstnl = $mysqli->query("SELECT standaardtekst_tekst FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$standaardteksten = $mysqli->query("SELECT standaardtekst_tekst_en FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
while ($NL_Tekst = mysqli_fetch_row($standaardtekstnl))
{
$label_Tekst = mysqli_fetch_row($standaardtekstlabel);
$EN_Tekst = mysqli_fetch_row($standaardteksten);
print '<form action="" method="POST">
<input type="text" name="standaardtekst_label" value=' . $label_Tekst[0] . '>
<textarea name="standaardtekst_tekst">' . $NL_Tekst[0] . '</textarea>
<textarea name="standaardtekst_tekst_en">' . $EN_Tekst[0] . '</textarea>
<input type="submit" value="update">
</form>';
}
?>
First of all, there is absolutely 0.0 reason why you're using 3 queries for the information you're trying to get. You can simply have: $standaardtekst = $mysqli->query("SELECT standaardtekst_label,standaardtekst_tekst,standaardtekst_en FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
Now regarding your question that is now probably obsolete:
Make the names of the input like this: standaardtekst_tekst[] saving it in an array.
You also need to have a unique(auto increment) key in your database like: id and put it in every form. You can even use the value of this field in the name like this: standaardtekst_tekst[$id].
You could edit your code a bit to look something like this:
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$q = $mysqli->query("SELECT standaardtekst_id, standaardtekst_label,
standaardtekst_tekst, standaard_tekst_tekst_en
FROM Standaardteksten
WHERE standaardtekst_account_pID='".$loggedinuserid."'");
while ($NL_Tekst = mysqli_fetch_row($standaardtekstnl))
{
$row = mysqli_fetch_row($q);
?>
<form action="" method="POST">
<input type="text" name="formData[<?= $row['id']; ?>][standaardtekst_label]" value="<?= $row['standaardtekst_label']; ?>">
<textarea name="formData[<?= $row['id']; ?>][standaardtekst_tekst]"><?= $row['standaardtekst_tekst']; ?></textarea>
<textarea name="formData[<?= $row['id']; ?>][standaardtekst_tekst_en]"><?= $row['standaardtekst_tekst_en']; ?></textarea>
<input type="submit" value="update">
</form>
<?php
}
?>
What I've done:
Made your 3 queries into a single query
Gave each form a unique id
Cleaned up the code a bit
This enables you to do the following:
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['formData'])) {
foreach ($_POST['formData'] as $id => $value) {
$stmt = $mysqli->query("UPDATE standaardtekst SET standaardtekst_label='".$value['standaadtekst_label']."', standaardtekst_tekst='".$value['standaardtekst_tekst']."', standaardtekst_tekst_en='".$value['standaardtekst_tekst_en']."' WHERE standaardtekst_id='".$id."'");
}
}
Thx for the help everyone. Everything is working right now.
This is the script i used to get it to work :-)
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$result = $mysqli->query("SELECT * FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$row_s = $result->fetch_assoc();
do{
print '<form action="" method="POST">
<input type="text" name="standaardtekst_label" value=' . $row_s['standaardtekst_label'] . '>
<textarea name="standaardtekst_tekst">' . $row_s['standaardtekst_tekst'] . '</textarea>
<textarea name="standaardtekst_tekst_en">' . $row_s['standaardtekst_tekst_en'] . '</textarea>
<input type="text" name="standaardtekst_ID" value="'. $row_s['standaardtekst_ID'] .'"/>
<input type="submit" value="update">
</form>';
} while($row_s = $result->fetch_assoc());
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['standaardtekst_ID']))
{
$updatesql= sprintf("UPDATE Standaardteksten SET standaardtekst_label='%s', standaardtekst_tekst='%s', standaardtekst_tekst_en='%s' WHERE standaardtekst_ID='%s'",
$_POST[standaardtekst_label],
$_POST[standaardtekst_tekst],
$_POST[standaardtekst_tekst_en],
$_POST[standaardtekst_ID]
);
$mysqli->query($updatesql);
echo "Het volgende wordt aangepast: <br />", "Label:", $_POST[standaardtekst_label], "<br />" , "NL tekst:", $_POST[standaardtekst_tekst], "<br />" , "EN tekst:", $_POST[standaardtekst_tekst_en];
echo "<meta http-equiv='refresh' content='1;url=/form.php'>";
}
?>

Database not updating correctly in PHP / MySQL [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I've got a database with a Users table which I'm trying to update.
Currently I have customers.php, which displays form fields with the user information so it can be updated.
This form points to edit_customer_processor.php , which takes the new values, puts them into a MYSQL query... and then despite the query working correctly when I query the DB via the PHPMyAdmin command line, the record doesn't update.
customers.php
<?php
session_start();
if(!$_SESSION["logged_in"]){
header("location:home.php");
die;
}
?>
<?php include 'header.html'; ?>
<div id='maincontent'>
<?php
if (isset($_GET["id"])){
$customer_id = $_GET["id"];
require_once('config.php');
$customer_query = "SELECT * FROM customer WHERE customer_id = $customer_id";
$customer_results = mysql_query($customer_query, $conn);
if (!$customer_results) {
die ("Error selecting car data: " .mysql_error());
}
else {
while ($row = mysql_fetch_array($customer_results)) {
echo "<h3>Edit Customer</h3>";
echo "<FORM method='post' action='edit_customer_processor.php'>";
echo '<p> Name: <input type="text" name="name" size = "40" value=' . $row[name] . '></p>';
echo '<p> Address: <input type="text" name ="address" size="40" value=' . $row[address] . '></p>';
echo '<p> Email: <input type="text" name="email" value=' . $row[email] . '></p>';
echo '<p> Phone: <input type ="text" name="phone" size="20" value=' . $row[phone] . '></p>';
echo '<input type ="hidden" name="customer_id" value="' . $row[customer_id] . '">';
echo '<input type ="hidden" name="formtype" value="edit_customer">';
echo '<input type="submit" name="submit" value= "Update">';
echo '</form>';
}
}
} else {
// If there isn't an ID, display the New Customer form and all customers below, with links
// to their edit pages.
echo "<h3>Enter new customer information and submit.</h3>";
echo "<FORM method='post' action='new_customer_processor.php'>";
echo '<p> Name: <input type="text" name="name" size = "40"></p>';
echo '<p> Address: <input type="text" name ="address" size="40"></p>';
echo '<p> Email: <input type="text" name="email"></p>';
echo '<p> Phone: <input type ="text" name="phone" size="20"></p>';
echo '<input type ="hidden" name="formtype" value="new_customer">';
echo '<input type="submit" name="submit" value= "Submit">';
echo '<input type ="reset" name="reset" value ="Reset">';
echo '</form>';
require_once('config.php');
echo "<h3>Current Customers</h3>";
$query = "SELECT * FROM customer";
$results = mysql_query($query, $conn);
if (!$results) {
die ("Error selecting customer data: " .mysql_error());
}
else {
// In the absence of an ID, all customers will be displayed down
// the bottom of the page
while ($row = mysql_fetch_array($results)) {
echo "<a href=customers.php?id=";
echo $row[customer_id];
echo "><p> $row[name] </p></a>";
echo "<p> $row[address] </p>";
echo "<p> $row[phone] </p>";
echo "<p> $row[email] </p>";
}
}
}
?>
Back to Customers Page
</div>
<?php include 'footer.html' ?>
edit_customer_processor.php
<?php include 'header.html' ?>
<div id="maincontent">
<?php
// Pulling in hidden customer ID from post value
$mysqli = new mysqli( 'localhost', 'root', 'root', 'w_c_a' );
// Check our connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
// Insert our data
$sql = mysql_query("UPDATE customer
SET name = '".mysql_real_escape_string($_POST['name'])."',
address = '".mysql_real_escape_string($_POST['address'])."',
phone = '".mysql_real_escape_string($_POST['phone'])."',
email = '".mysql_real_escape_string($_POST['email'])."'
WHERE customer_id='".mysql_real_escape_string($_POST['customer_id'])."'");
$update = $mysqli->query($sql);
echo "Customer updated: ";
echo "<a href=customers.php?id=" . $_POST['customer_id'] . ">";
echo "Back to Edit Customer</a>";
?>
</div>
<?php include 'footer.html' ?>
And when I echo the MYSQL query, I get:
UPDATE customer SET name = 'Kellyassdsa', address = 'ads', phone = '0260123123', email = 'asdasd' WHERE customer_id='1'
Which works when I put it in PHPMyAdmin.
I know it'll be some boneheaded little mistake, but I've been trying to get this work for ages now. Any ideas?
Maybe your program just can't connect to your MySQL database.
$customer_results = mysql_query($customer_query, $conn);
I can't see where you gave a value to the var $conn.
If the problem is connection problem then we might need your database info like the name of your table in PhpMyAdmin.
your problem is...
$sql = mysql_query(..);
$update = $mysqli->query($sql);
it should be
$sql = 'UPDATE ...';
$update = $mysqli->query($sql);
i think problem occurs due to line break. pleas make a query in single line without line break.
$sql = mysql_query("UPDATE customer SET name = '".mysql_real_escape_string($_POST['name'])."',address = '".mysql_real_escape_string($_POST['address'])."', phone = '".mysql_real_escape_string($_POST['phone'])."', email = '".mysql_real_escape_string($_POST['email'])."' WHERE customer_id='".mysql_real_escape_string($_POST['customer_id'])."'");
Hope this helps..

Display List of the array after inserting the form

I use HTML form to insert data to a database table. What I want to do is to display the data I inserted using the HTML form. I use associative arrays to get the right data from the database. But I can only display only one row from the table. I don't know why my code doesn't display the other data I inserted.
Here is my code:
<?php
$part_insert_message = "";
enter code here
session_start();
$inserted_parts = array();
$part_inserted_id;
if(isset($_POST['submit'])) {
require "/Basics/Mysql_Connect/mysql_connect.php";
$sql="INSERT INTO Parts (SKU, Part, Description, Quantity, Price)
VALUES
('$_POST[sku]', '$_POST[categories]', '$_POST[description]', '$_POST[quantity]', '$_POST[price]')";
$result = mysqli_query($con, $sql);
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
$part_inserted_id = mysqli_insert_id($con);
$inserted_parts[$part_inserted_id] = $part_inserted_id;
// store session data
$_SESSION['views']= $inserted_parts;
$part_insert_message = "ID: " . $part_inserted_id . " Part: " . $_POST['sku'];
mysqli_close($con);
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
if(isset($_SESSION['views'])){
$inserted_parts = $_SESSION['views'];
}
if(!empty( $inserted_parts )) {
require "/Basics/Mysql_Connect/mysql_connect.php";
foreach($inserted_parts as $key => $value){
$sql = "SELECT * FROM Parts WHERE PartID='$key'";
$result = mysqli_query($con, $sql);
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
$productCount = mysqli_num_rows($result); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($result)){
$partID = $row["PartID"];
$sku = $row["SKU"];
$part = $row["Part"];
$description = $row["Description"];
$quantity = $row["Quantity"];
$price = $row["Price"];
$product_list .= "Product ID: $partID - <strong>$sku</strong> - $$price - <em>Part $part</em> <a href='Add_Delete_Part.php?deleteid=$partID'>delete</a><br />";
}
}else {
$product_list = "You have no products listed in your store yet";
}
}
mysqli_close($con);
}
?>
<?php
require "/Basics/Mysql_Connect/mysql_connect.php";
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = "DELETE FROM Parts WHERE PartID='$id_to_delete'";
$result = mysqli_query($con, $sql);
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
// unlink the image from server
// // Remove The Pic -------------------------------------------
// $pictodelete = ("../inventory_images/$id_to_delete.jpg");
// if (file_exists($pictodelete)) {
// unlink($pictodelete);
// }
header("location: Add_Delete_Part.php");
exit();
}
mysqli_close($con);
?>
<html>
<body>
<div>
<h2>Part</h2>
<form action="Add_Delete_Part.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
SKU#: <input type="text" name="sku"><br>
Part: <select name="categories">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select><br>
Description: <input type="text" name="description"><br>
Quantity: <input type="text" name="quantity"><br>
Price: <input type="text" name="price"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php echo $part_insert_message; ?>
<h3>Fits:</h3>
<?php echo $product_list; ?>
<!--<form action="Add_Images.php" method="post">
Select images: <input type="file" name="img" multiple><input type="submit" value="Upload">
</form>
-->
</div>
</body>
</html>

PHP Issue with deleting from MySQL

I do have programming experience, but new to php. I do have an issue with an example I was doing from this tutorial. I looked over it millions of times, googled, ect ect. I don't have an idea why my code isnt working.
The purpose is to basically just test inserting and deleting in sql from php, using a button for Add Record and Delete Record. The Add record button works perfectly, but delete doesnt do a thing other than reload the page. Heres the code...
<?php // sqltest.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['type']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
if (isset($_POST['delete']) && $isbn != "")
{
echo "worked!!!!!!!!!!!!!!";
$query = "DELETE FROM classics WHERE isbn='$isbn'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
//if (!mysql_query($query, $db_server))
//echo "DELETE failed: $query" . mysql_error();
}
else
{
echo "nooooooooooooooooooo";
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$type', '$year', '$isbn')";
if (!mysql_query($query, $db_server))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Type $row[2]
Year $row[3]
ISBN $row[4]
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="$row[4]" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
I have looked over this many times, still no idea why this won't work. Is it the for loop that is making this button not work? Note, you will see echo "worked!!!"; and in the else echo "noooooooo"; that was for me to test whether the button was being tested, yet nothing prints. So maybe i missed something in the button code itself? Also, no errors are printed, and my editor (and myself) have missed the syntax error (if thats the case).
The code for the delete button is at the end, before I closed the DB.
Thanks for your help in advance.
Your problem is your first if block.
You're checking for the presence of the posted variables author title type year isbn. Whereas in your delete code the only variables sent are delete and isbn. Therefore the first if block is completely missed (including the delete code).
You need to modify your first if to be if(isset($_POST)) { // a form has been posted. Then it should work.
Another way to do it:
if(isset($_POST['delete']) && isset($_POST['isbn']) && !empty($_POST['isbn'])){
//delete code here
}
if(isset($_POST['author']) && isset($_POST['title']) && isset....){
// insert code here
}
EDIT: rewritten code:
<?php // sqltest.php
// I don't know what's in here, so I've left it
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST))
{
if (isset($_POST['delete']) && !empty($_POST['isbn']))
{
echo "Deleting";
$query = "DELETE FROM classics WHERE isbn='".mysql_real_escape_string($_POST['isbn'])."'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
}
else
{
echo "Inserting";
$query = "INSERT INTO classics VALUES ('".mysql_real_escape_string($_POST['author'])."', '".mysql_real_escape_string($_POST['title'])."', '".mysql_real_escape_string($_POST['type'])."', '".mysql_real_escape_string($_POST['year'])."', '".mysql_real_escape_string($_POST['isbn'])."')";
if (!mysql_query($query))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
// you don't need echo's here... just html
?>
<form action="sqltest.php" method="post">
<pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre>
</form>
<?php
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
// a better way to do this:
while($row = mysql_fetch_array($result)){
?>
<pre>
Author <?php echo $row[0]; ?>
Title <?php echo $row[1]; ?>
Type <?php echo $row[2]; ?>
Year <?php echo $row[3]; ?>
ISBN <?php echo $row[4]; ?>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="<?php echo $row[4]; ?>" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
<?php
}
mysql_close($db_server);
?>
Verify the method you used in your form. Make sure it's POST like this:
Form action="yourpage.php" method="POST"
and in your code above, replace the following:
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
with
$author = $_POST['author'];
$title = $_POST['title'];
$type = $_POST['type'];
$year = $_POST['year'];
$isbn = $_POST['isbn'];
Finally, there is no need to check again if the $isbn is not null as you did it in your isset() method. So remove $isbn!="" in the if below:
if (isset($_POST['delete']) && $isbn != "")
{
}
becomes:
if (isset($_POST['delete']))
{
}
Since you are testing, checking if the user clicked the delete button is of less importance. So you can also remove it for a while and add it later because you are sure that, that code is accessible after clicking the delete button.
You have no form field named delete, so it is impossible for your delete code path to ever be taken.
I'm guessing you're tryign to use the value of the submit button to decide what to do? In that case, you're also missing a name attribute on the submit button - without that, it cannot submit any value with the form. You probably want:
<input type="submit" name="submit" value="DELETE RECORD" />
and then have
if (isset($_POST['submit']) && ($_POST['submit'] == 'DELETE RECORD')) {
...
}

web form does not add or delete from mysql table

I'm working on a basic web form (using PHP and smarty templates) that allows users to add and delete data from a mysql database table. The data and form display fine, but nothing happens when a user tries to add or delete records from the table(not even the "cannot delete/add record' error message displays). Here is what the code looks like:
<?php //smartytest.php
$path =$_SERVER['DOCUMENT_ROOT'];
require "$path/Smarty/Smarty.class.php";
$smarty = new Smarty();
$smarty->template_dir = "$path/temp/smarty/templates";
$smarty->compile_dir= "$path/temp/smarty/templates_c";
$smarty->cache_dir="$path/temp/smarty/cache";
$smarty->config_dir="$path/temp/smarty/configs";
require_once ("$path/phptest/login.php");
$db_server=mysql_connect($db_hostname, $db_username, $db_password);
if(!$db_server) die('unable to connect to MySQL: '. mysql_error());
mysql_select_db($db_database) or die("unable to select database: " . mysql_error());
if(isset($_POST['author'])&&
isset($_POST['title'])&&
isset($_POST['category'])&&
isset($_POST['year'])&&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$category=get_post('category');
$year = get_post('year');
$isbn =get_post('isbn');
if (isset($_POST['delete']) && $isbn !='')
{
$query= "DELETE FROM classics WHERE isbn='$isbn'";
if (!mysql_query($query))
{
echo "DELETE failed: $query<br>". mysql_error() . "<p>";
}
}
else
{
$query = "INSERT INTO classics VALUES" . "('$author','$title', '$category', '$year', '$isbn')";
if (!mysql_query($query))
{
echo "INSERT failed: $query<br>" . mysql_error() . "<p>";
}
}
}
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: ". mysql_error());
$rows = mysql_num_rows($result);
for ($j=0; $j < $rows; ++$j)
{
$results[] = mysql_fetch_array($result);
}
mysql_close($db_server);
$smarty->assign('results', $results);
$smarty->display("smartytest.tpl");
function get_post($var)
{
return mysql_escape_string($_POST[$var]);
}
?>
Also, here is the Smarty template file:
<html><head>
<title>Smarty Test</title>
</head><body>
<form action="/phptest/smartytest.php" method="post"><pre>
Author <input type="text" name="author">
Title<input type="text" name="title">
Category<input type="text" name="category">
Year<input type="text" name="year">
ISBN<input type="text" name="isbn">
<input type="submit" value="ADD RECORD">
</pre></form>
{section name=row loop=$results}
<form action="/phptest/smartytest.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="isbn" value="{$results[row].isbn}">
<pre>
Author {$results[row].author}
Title {$results[row].title}
Category {$results[row].category}
Year {$results[row].year}
ISBN {$results[row].isbn}
<input type="submit" value="DELETE RECORD"></form>
</pre>
{/section}
</body></html>
My best guess is that there is something wrong with the nested if statements (which may be why not even the error message is displaying), but I've double checked the code and it looks good (at least to me). Does anyone notice anything wrong with this? I can post a screen of what the page looks like if that will help.
You are checking for the existence of author, title, category, year, isbn with isset(..) before checking to see what type of action was taken. There variables (like $_POST['author'] are not set. Reason is that you have multiple forms on the page. Only the inputs that are within the form that is submitted are available in $_POST.
In this case, you could simply do:
if (isset($_POST['delete'])
&& isset($_POST['isbn'])
&& strlen($_POST['isbn'])) {
// Remove record code here
}
else {
// Add record code here
}

Categories