How to use forms to update SQL - php

I'm trying to make a form that uses a drop down, radio buttons, text field, textarea, and a hidden value(the time) then takes that information from that form and updates SQL database.
My form is below and it all loads correctly but I'm having issues updating the values and trying to figure out how to make the radio buttons and dropdowns to work since I can't make the value php code and need to pass the value. Everything I'm finding on the web is how to do text fields where the user types something.
When I select update it just submits the data but nothing changes. On my update.php I have a sanitize function at the very end and am unsure how to pass the variables in. Do I create an array named $var and input all my variables into it or pass each variable at a time?
I've been searching the web for HOW TO's and am currently reading two books but they don't go into enough detail so thanks for any assistance.
control.php
<?php
session_start();
if( !isset($_SESSION['myusername']) ){ header("Location: login.php"); }
?>
<?php
require("../../system/templates/includes/constants.php");
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(!$connection) { die("Database connection failed: " .mysql_error()); }
$db_select = mysql_select_db(DB_NAME,$connection);
if(!$db_select) { die("Database selection failed: " . mysql_error()); }
?>
<form method="post" action="update.php">
<select name="name" required="true" value="<?php echo $row['name']; ?>">
<?php
$query="SELECT id, name FROM modules";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result)) {
echo "<option value=\"" . $row['id'] . "\">" . $row['name'] . "</option>";
}
?>
</select>
<br />
Select Status:
Red <input type="radio" value="red" name="status" />
Yellow <input type="radio" value="yellow" name="status" />
Green <input type="radio" checked="checked" value="green" name="status" />
<br />
Reason:
<br />
<select name="reason" required="true">
<option value="0" selected="selected" value="">Select Reason</option>
<option value="ONLINE">Online</option>
<option value="MAINTENANCE">Maintenance</option>
<option value="ERROR">Error</option>
<option value="OFFLINE">Offline</option>
<option value="">No Reason</option>
</select>
<br />
ETA:
<br />
<input type="text" name="eta" value="<?php echo $row['eta']; ?>" maxlength="8" />
<br />
Description:
<br />
<textarea rows="5" cols="30" name="explanation" wrap="hard" required="true" maxlength="320" value="<?php echo $row['description']; ?>" /></textarea>
<br />
<div align="right">
<input name="update" type="submit" value="Update"/>
<input type="hidden" name="last_updated" value="<?php $mysqldate = date ('H:i'); $phpdate = strtotime ( $mysqldate );?> />
</form>
update.php
<?php
print_r(_POST);
if(isset($POST['update']))
{
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(! $connection)
{
die('Could not connect: ' .mysql_error());
}
$name = $POST['name'];
$status = $POST['status'];
$reason = $POST['reason'];
$eta = $POST['eta'];
$description = $POST['description'];
$last_updated = $POST['last_updated'];
$updated_by = $POST['updated_by'];
$sql = "UPDATE module SET status = $status , reason = $reason , eta = $eta , description = $description , last_updated = $last_updated , updated_by = $updated_by WHERE name = $name";
mysql_select_db('status');
$retval = mysql_query ( $sql, $connection);
if (!retval)
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully";
mysql_close($connection);
} else {
// not sure what to do here
}
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
function sanitizeMySQL($var)
{
$var = mysql_real_escape_string($var);
$var = satnizeString($var);
return $var;
}
header("Location: control.php");
?>
As always I greatly appreciate any assistance anyone can offer. I'm still in the very early stages of learning this and this website and community has helped me more than any book/tutorial I've read so far.

Your SQL statement needs quotation marks for each parameter.
$sql = "UPDATE module SET status = '$status' , reason = '$reason' , eta = '$eta' , description = '$description' , last_updated = '$last_updated' , updated_by = '$updated_by' WHERE name = '$name' ";
As for the sanitizeString() function, it only takes in one string at a time. Maybe something like the one below may be simple and clean:
$params = array($name, $status, $reason); // put all your params in here
foreach ($params as &$p) { // the '&' before $p is essential, so do not forget it
$p = sanitizeString($p);
}
Hope it helps.

Related

Using AJAX How can I generate selections for a dropdown menu based on records available in a database?

Using AJAX How can I generate selections for a dropdown menu based on records available in a database?.
How can then use these selections to prefill a form with record/row data from a database when selected?
Heres a mock up I created of what I'm trying to do:
http://oi58.tinypic.com/2urb2ae.jpg
PHP FILE: contact_form.php
-----------------------------------------------------------
<?php
define('DB_NAME', 'xxx');
define('DB_USER', 'xxx');
define('DB_PASSWORD', 'xxx');
define('DB_HOST', 'xxx');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$connection){
die('Database connection failed: ' . mysqli_connect_error());
}
$db_selected = mysqli_select_db($connection, DB_NAME);
if(!$db_selected){
die('Can\'t use ' .DB_NAME . ' : ' . mysqli_connect_error());
}
echo 'Connected successfully';
if (isset($_POST['itemname'])){
$itm = $_POST['itemname'];
}
else {
$itm = '';
}
if($_POST['mile']){
$mi = $_POST['mile'];
}else{
echo "Miles not received";
exit;
}
if($_POST['email']){
$email = $_POST['email'];
}else{
echo "email not received";
exit;
}
$sql = "INSERT INTO seguin_orders (itemname, mile, email)
VALUES ('$itm', '$mi', '$email')";
if (!mysqli_query($connection, $sql)){
die('Error: ' . mysqli_connect_error($connection));
}
CONACT FORM: formz.php
------------------------------------------------------------------------------
<html>
<header>
</header>
<body>
<form action="/demoform/contact_form.php" class="well" id="contactForm" method="post" name="sendMsg" novalidate="">
<big>LOAD PAST ORDERS:</big>
<select id="extrafield1" name="extrafield1">
<option value="">Please select...</option>
<?php
$email = $_POST['email'];
$query="select * from tablename WHERE email={$_POST['email']}";
$res=mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($res))
{
?>
<option value="<?php echo $row['fieldname']; ?>"><?php echo $row['fieldname']; ?></option>
<?php
}
?>
</select>
</br>
<input type="text" required id="mile" name="mile" placeholder="Miles"/>
</br>
<input id="email" name="email" placeholder="Email" required="" type="text" value="demo#gmail.com" readonly="readonly"/>
</br>
<input id="name" name="itemname" placeholder="ITEM NAME 1" required="" type="text" />
</br>
<input type="reset" value="Reset" />
<button type="submit" value="Submit">Submit</button>
</form>
</body>
</html>
Using an exemple, let's assume you want to fill the "name" select based on the option selected at the "gender" select:
<select name="gender" id="gender">
<option value="m">Male</select>
<option value="f">Female</select>
</select>
When nothing is selected yet, the "name" select is empty:
<select name="name" id="name">
<option value="NULL">Please select a gender first</option>
</select>
So, what you gotta do is: when the gender select got some selection, you populate the name select with values based on the gender select option.
$(document).ready(function() {
$('select#gender').change(function(){
$('select#name').load('LOAD_NAMES_BASED_ON_GENDER.php?gender='+$(this).val());
});
});
And your PHP file responsible for loading the names based on gender should look like:
$gender = $_GET['gender'];
$list = // the way you retrieve your list of names from your DB
And then you loop this $list into an list of options, such like:
foreach($list as $key=>$value)
echo '<option value="$key">$value</option>';
This simple.
PS: the load() function is kind of an alias for the $.ajax request, given that the only purpose here is to retrieve data.

PHP Header 302 Found

I am trying to go back to the page i came from after the update is submitted.
the $pagefrom gets populated from the page before. that works fine. I get redirected to a page that says 302 found but its the same url as my current page.
<?php
{
$pagefrom= $_POST['pagename'];
echo $pagefrom;
if(isset($_POST['add']))
{
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$Reg_F_Name = addslashes ($_POST['Reg_F_Name']);
$Reg_L_Name = addslashes ($_POST['Reg_L_Name']);
}
else
{
$Req_F_Name = $_POST["Req_F_Name"];
$Reg_L_Name = $_POST["Reg_L_Name"];
}
$Req_ID = $_POST["Req_ID"];
$Req_F_Name = $_POST["Req_F_Name"];
$Reg_L_Name = $_POST["Reg_L_Name"];
$Reg_Email = $_POST["Reg_Email"];
$Reg_Mod_Request = $_POST["Reg_Mod_Request"];
$Reg_Address_1 = $_POST["Reg_Address_1"];
$Reg_Address_2 = $_POST["Reg_Address_2"];
$Reg_City = $_POST["Reg_City"];
$Reg_State = $_POST["Reg_State"];
$Reg_Zip_Code= $_POST["Reg_Zip_Code"];
$Reg_ID= $_POST["Reg_ID"];
$Reg_Phone = $_POST["Reg_Phone"];
$Reg_Phone= str_replace("-","","$Reg_Phone");
$Reg_Approval_Status= $_POST["Reg_Approval_Status"];
$Reg_Status= $_POST["Reg_Status"];
$sql= "UPDATE $dbtable SET
Reg_F_Name = '$Reg_F_Name',
Reg_L_Name = '$Reg_L_Name',
Reg_Phone = '$Reg_Phone',
Reg_Email = '$Reg_Email',
Reg_Mod_Request = '$Reg_Mod_Request',
Reg_Address_1 = '$Reg_Address_1',
Reg_Address_2 = '$Reg_Address_2',
Reg_City = '$Reg_City',
Reg_State = '$Reg_State',
Reg_Zip_Code = '$Reg_Zip_Code',
Reg_Approval_Status='$Reg_Approval_Status',
Reg_Status='$Reg_Status'
WHERE Reg_ID = '$Reg_ID'";
mysql_select_db($database);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
mysql_close($conn);
header('Location: '.$pagefrom);
}
else
{
?>
<?php
$con=mysqli_connect($dbhost, $dbuser, $dbpass, $database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = mysqli_query($con, "SELECT * FROM $dbtable WHERE Reg_ID = '$Reg_ID'");
?>
<form method="post" action="" style="width: 500px">
<fieldset>
<p style="text-align: center">Update A Prayer Request</p>
<div style="width: 500px; float: left">
<?php
while($rows = mysqli_fetch_array($query))
{
?>
<input type="hidden" name="Reg_ID" value="<?=$rows['Reg_ID']?>">
Please pray for:
<br />First Name: <input name="Reg_F_Name" type="text" id="Reg_F_Name" value="<? echo $rows['Reg_F_Name']; ?>">
<br />Last Name: <input name="Reg_L_Name" type="text" id="Reg_L_Name" value="<? echo $rows['Reg_L_Name']; ?>">
<br />Original Prayer Request:
<br/><? echo $rows['Reg_Request']; ?>
<br />Update Prayer Request:
<br /><textarea name="Reg_Mod_Request" type="varchar" id="Reg_Mod_Request" rows="5" cols="30"><? echo $rows['Reg_Mod_Request']; ?></textarea>
<br />Primary Address: <input name="Reg_Address_1" type="varchar" id="Reg_Address_1" value="<? echo $rows['Reg_Address_1']; ?>">
<br />Secondary Address:<input name="Reg_Address_2" type="varchar" id="Reg_Address_2" value="<? echo $rows['Reg_Address_2']; ?>">
<br />City:<input name="Reg_City" type="char" id="Reg_City" value="<? echo $rows['Reg_City']; ?>">
<br />State:<input name="Reg_State" type="char" id="Reg_State" value="<? echo $rows['Reg_State']; ?>">
<br />Zip:<input name="Reg_Zip_Code" type="char" id="Reg_Zip_Code" value="<? echo $rows['Reg_Zip_Code']; ?>">
<br />Phone Number (555-555-5555):<input name="Reg_Phone" type="char" id="Reg_Phone" value="<? echo $rows['Reg_Phone']; ?>">
<br />Email Address:<input name="Reg_Email" type="varchar" id="Reg_Email" value="<? echo $rows['Reg_Email']; ?>">
<br />Approval Status: <select id="Approval" name="Approval">
<!--Call run() function-->
<option value="0" <?php echo $rows['Reg_Approval_Status'] == "0" ? "selected" : '' ?>>Waiting Approval</option>
<option value="1" <?php echo $rows['Reg_Approval_Status'] == "1" ? "selected" : '' ?>>Accept</option>
<option value="2" <?php echo $rows['Reg_Approval_Status'] == "2" ? "selected" : '' ?>>Decline</option>
</select>
<br />Enabled Request: <select id="Activate" name="Activate">
<option value="0" <?php echo $rows['Reg_Status'] == "0" ? "selected" : '' ?>>Disable</option>
<option value="1" <?php echo $rows['Reg_Status'] == "1" ? "selected" : '' ?>>Enable</option>
</select>
</div>
<input name="add" type="submit" id="add" value="Update Prayer Request">
</fieldset>
</form>
<?php
}
}
mysql_close();
}
?>
I think something is wrong with
header('Location: '.$pagefrom);
but everything i try i still can not get it to reload the page before.
Remove echo $pagefrom; from the top of your script or move the header line above it. Headers can not be sent after output has started.
See: header
Try adding die(); the next line you use Header('Location: ....'); - if you don't the php will continue working further.
Also you probably want to use the form in the page the source code is from. Here you dont provide the pagename anymore therefore when you use form from this page - the $pagefrom is empty and redirection goes to current page.
Try adding it as hidden input for this form, and it should work.

Table will not update PHP

I get the id from the page before. Everything on this page gets populated from the database just fine. when i hit add button the database does not get populated. Everything looks good to me but i can no figure out why it wont update. I am new to php. I am sure my code is very sloppy
<?php
{
$Reg_ID = $_POST['id'];
$dbhost = '';
$dbuser = '';
$dbpass = '';
$database ='';
$table = '';
if(isset($_POST['add']))
{
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$Reg_F_Name = addslashes ($_POST['Reg_F_Name']);
$Reg_L_Name = addslashes ($_POST['Reg_L_Name']);
}
else
{
$Req_F_Name = $_POST["Req_F_Name"];
$Reg_L_Name = $_POST["Reg_L_Name"];
}
$Req_F_Name = $_POST["Req_F_Name"];
$Reg_L_Name = $_POST["Reg_L_Name"];
$Reg_Phone = $_POST["Reg_Phone"];
$Reg_Email = $_POST["Reg_Email"];
$Reg_Mod_Request = $_POST["Reg_Mod_Request"];
$Reg_Address_1 = $_POST["Reg_Address_1"];
$Reg_Address_2 = $_POST["Reg_Address_2"];
$Reg_City = $_POST["Reg_City"];
$Reg_State = $_POST["Reg_State"];
$Reg_Zip_Code= $_POST["Reg_Zip_Code"];
$Reg_ID= $_POST["Reg_ID"];
$Reg_Phone= str_replace("-","","$Reg_Phone");
$sql = "UPDATE $table".
"(Reg_F_Name,Reg_L_Name, Reg_Phone, Reg_Email, Reg_Mod_Request, Reg_Address_1, Reg_Address_2, Reg_City, Reg_State, Reg_Zip_Code) ".
"VALUES('$Reg_F_Name','$Reg_L_Name','$Reg_Phone','$Reg_Email','$Reg_Mod_Request','$Reg_Address_1','$Reg_Address_2','$Reg_City','$Reg_State','$Reg_Zip_Code')".
"WHERE Reg_ID = '$Reg_ID'";
mysql_select_db($database);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{
?>
<?php
$con=mysqli_connect($dbhost, $dbuser, $dbpass, $database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = mysqli_query($con, "SELECT * FROM Request WHERE Reg_ID = '$Reg_ID'");
?>
<form method="post" action="viewrequests.php" style="width: 500px">
<fieldset>
<input type='hidden' name='__token_timestamp__' value='1397526990'>
<input type='hidden' name='__token_val__' value='34a10d1cfc4b20e45c901e83624677ad'>
<p style="text-align: center">Update Prayer Request</p>
<div style="width: 500px; float: left">
<?php
while($rows = mysqli_fetch_array($query))
{
?>
Please pray for:
<br />First Name: <input name="Reg_F_Name" type="text" id="Reg_F_Name" value="<? echo $rows['Reg_F_Name']; ?>">
<br />Last Name: <input name="Reg_L_Name" type="text" id="Reg_L_Name" value="<? echo $rows['Reg_L_Name']; ?>">
<br />Prayer Request: <? echo $rows['Reg_Request']; ?>
<br />Update Prayer Request:
<br /><textarea name="Reg_Mod_Request" type="varchar" id="Reg_Mod_Request" rows="5" cols="30"><? echo $rows['Reg_Request']; ?></textarea>
<br />Primary Address: <input name="Reg_Address_1" type="varchar" id="Reg_Address_1" value="<? echo $rows['Reg_Address_1']; ?>">
<br />Secondary Address:<input name="Reg_Address_2" type="varchar" id="Reg_Address_2" value="<? echo $rows['Reg_Address_2']; ?>">
<br />City:<input name="Reg_City" type="char" id="Reg_City" value="<? echo $rows['Reg_City']; ?>">
<br />State:<input name="Reg_State" type="char" id="Reg_State" value="<? echo $rows['Reg_State']; ?>">
<br />Zip:<input name="Reg_Zip_Code" type="char" id="Reg_Zip_Code" value="<? echo $rows['Reg_Zip_Code']; ?>">
<br />Phone Number (555-555-5555):<input name="Reg_Phone" type="char" id="Reg_Phone" value="<? echo $rows['Reg_Phone']; ?>">
<br />Email Address:<input name="Reg_Email" type="varchar" id="Reg_Email" value="<? echo $rows['Reg_Email']; ?>">
<br /><br />
</div>
<input name="add" type="submit" id="add" value="Update Prayer Request">
</fieldset>
</form>
<?php
}
}
mysql_close();
}
?>
I think the problem has something to do with
$sql = "UPDATE $table".
"(Reg_F_Name,Reg_L_Name, Reg_Phone, Reg_Email, Reg_Mod_Request, Reg_Address_1, Reg_Address_2, Reg_City, Reg_State, Reg_Zip_Code) ".
"VALUES('$Reg_F_Name','$Reg_L_Name','$Reg_Phone','$Reg_Email','$Reg_Mod_Request','$Reg_Address_1','$Reg_Address_2','$Reg_City','$Reg_State','$Reg_Zip_Code')".
"WHERE Reg_ID = '$Reg_ID'";
But i am not sure. Any help would be greatly appreciated.
echo $sql output
UPDATE Request (Reg_F_Name,Reg_L_Name, Reg_Phone, Reg_Email, Reg_Mod_Request, Reg_Address_1,
Reg_Address_2, Reg_City, Reg_State, Reg_Zip_Code) VALUES('joe','qwea','4055554321',
'Fell off windmill. Broken legs possibly going to l','Fell off windmill.',
'4059 Mt Lee Dr','','Altus','OK','73521')
WHERE Reg_ID = ''Could not enter data: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right syntax to use near
'(Reg_F_Name,Reg_L_Name, Reg_Phone, Reg_Email, Reg_Mod_Request, Reg_Address_1, Re' at line 1
you need to put regid in a hidden field
<input type="hidden" name="Reg_ID" value="<?=$row['Reg_ID']?>">
so now you'll get this values in $_POST['Reg_ID']
or try like this
"UPDATE tablename".
"SET Reg_F_Name ='{$Reg_F_Name}',Reg_L_Name='{$Reg_L_Name}', Reg_Phone='{$Reg_Phone}', Reg_Email='{$Reg_Email}', Reg_Mod_Request='{$Reg_Mod_Request}', Reg_Address_1='{$Reg_Address_1}', Reg_Address_2='{$Reg_Address_2}', Reg_City='{$Reg_City}', Reg_State='{$Reg_State'}, Reg_Zip_Code='{$Reg_Zip_Code}' ".
"WHERE Reg_ID = '{$Reg_ID}'";
You are mixing INSERT syntax http://dev.mysql.com/doc/refman/5.6/en/insert.html
INSERT INTO tbl (columns) VALUES (values)
with UPDATE syntax http://dev.mysql.com/doc/refman/5.0/en/update.html
UPDATE tbl SET column=value WHERE column=value
Try something like
UPDATE $table SET
Reg_F_Name = '$Reg_F_Name',
Reg_L_Name = '$Reg_L_Name',
Reg_Phone = '$Reg_Phone',
Reg_Email = '$Reg_Email',
Reg_Mod_Request = '$Reg_Mod_Request',
Reg_Address_1 = '$Reg_Address_1',
Reg_Address_2 = '$Reg_Address_2',
Reg_City = '$Reg_City',
Reg_State = '$Reg_State',
Reg_Zip_Code = '$Reg_Zip_Code'
WHERE Reg_ID = '$Reg_ID'
Also, it looks like $Reg_ID is not set since you have
WHERE Reg_ID = ''
in your echo'ed sql. Add it as a hidden element to your form, so it is reset on form submit
<input type='hidden' name='id' value='<?php echo $Reg_ID; ?>'>

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')) {
...
}

advice on php post operation not running

I have donation page which when the user clicks donate it posts the data to a php file named test.php I am trying this out my first trying to echo the first name and last name but this is not working ultimately I want this php page to run a MySQL query to update the total_Donation row within a database, here is my main php page first.
Database code which sits at top of file
<?php
$con = mysql_connect("localhost","root","null");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("snr", $con);
$names_sql = "SELECT first_Name, last_Name FROM donate WHERE user_ID > 0";
$names_query = mysql_query($names_sql)or die(mysql_error());
$rsNames= mysql_fetch_assoc($names_query);
if(isset($_POST['donation']) && $_POST['donation'] != '')
{
$donation = mysql_real_escape_string($_GET['donation']);
$fname = mysql_real_escape_string($_GET['first_Name']);
$lname = mysql_real_escape_string($_GET['last_Name']);
$donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + '{$donation}' WHERE first_Name = '{$fname}' AND last_Name = '{$lname}'";
}
mysql_close($con);
?>
Here is my form section of html
form method ="post" action="test.php">
<table>
<tr><td><label>Runner:</label></td>
<td>
<select>
<?php do{?>
<option> <?php echo $rsNames['first_Name'];?> <?php echo $rsNames['last_Name'];?></option>
<?php } while ( $rsNames= mysql_fetch_assoc($names_query))?>
</select>
</td>
</tr>
<tr><td><label>Donation £</label></td><td><input type="text" maxlength="9" value="0.00" name="donation"/></td></tr>
<tr><td><input id="submit" type="submit" value="DONATE"/></td></tr>
</table>
</form>
the option gets all the first names and last names fine when the user hits donate I want it to run the $donation_sql but all i get are errors saying unidentified index, I'm even trying the below in the test.php to simply just echo the first_Name this is giving the same error.
<?php
echo $_POST['first_Name'];
?>
Can someone please help me with this, thanks.
index.php
<?php
$con = mysql_connect("localhost","root","null");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("snr", $con);
$names_sql = "SELECT first_Name, last_Name FROM donate WHERE user_ID > 0";
$names_query = mysql_query($names_sql)or die(mysql_error());
?>
<form method ="post" action="test.php">
<table>
<tr><td><label>Runner:</label></td>
<td>
<select name="name">
<?php
while($list = mysql_fetch_array($names_query))
{
?>
<option value="<?php echo $list['first_Name'] . ' ' . $list['last_Name']; ?>">
<?php echo $list['first_Name'] . ' ' . $list['last_Name']; ?>
</option>
<?php
}
?>
</select>
</td>
</tr>
<tr><td><label>Donation £</label></td><td><input type="text" maxlength="9" value="0.00" name="donation" /></td></tr>
<tr><td><input id="submit" type="submit" name="send" value="DONATE"/></td></tr>
</table>
</form>
test.php
<?php
$con = mysql_connect("localhost","root","null");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("snr", $con);
if(isset($_POST['donation']) && $_POST['donation'] != '')
{
$names = explode(' ',$_POST['name']);
$first_name= $names[0];
$last_name= $names[1];
$donation = mysql_real_escape_string($_POST['donation']);
$fname = mysql_real_escape_string($first_name);
$lname = mysql_real_escape_string($last_name);
$donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + '" .$donation. "' WHERE first_Name = '" .$fname. "' AND last_Name = '" .$lname. "'";
echo 'DEBUG (remove after OK): <br>' .$donate_sql. '<br>';
$res = mysql_query($donate_sql);
echo 'Thanks ' .$first_name. ' ' .$last_name. '<br>';
}
mysql_close($con);
?>
That´s it!
\make sure you set name for select and you have valua attr in option tag
<select name="first_Name">
<otpion value="<?php echo $rsNames['first_Name'];?>"><?php echo $rsNames['first_Name'];?>
<?php echo $rsNames['last_Name'];?>
</option>
</select>
YOu need to give a name attribute to the select:
<select name="first_Name">
<?php while ( $rsNames= mysql_fetch_assoc($names_query)):?>
<option value="<?php echo htmlspecialchars($rsNames['first_Name']).' '.htmlspecialchars($rsNames['last_Name']);?>"> [option displayed to the user here]</option>
<?php endwhile;?>
</select>
And of course use the $_POST array, not the $_GET, since you're using the POST method.

Categories