Allow user to delete profile information - php

I'm trying to create a form that displays current service information for a user on their profile and then allows them to select a check box for one or more services they provide and then hit a delete button to remove the service(s) related to the check box. Each service has a unique ID and so I'm assuming I need to use this so that the query knows what to delete.
Here is relevant code and the form I am using:
<?php
if (isset($_POST['OddJobName']) && isset($_POST['Description']) && isset($_POST['DaysAvailable']) && empty($errors) === true){//if (empty($_POST) === false && empty($errors) === true) { //if (isset(empty($_POST['OddJobName'])) && isset(empty($_POST['Description'])) && isset(empty($_POST['DaysAvailable'])) === false && empty($errors) === true)
$daysavailable='';
foreach ($_POST['DaysAvailable'] as $value)
{
$daysavailable .=$value." ";
}
$Delete_Oddjob = array (
'MemberID' => $MemberID,
'OddJobID' => $_POST['OddJobID'],
'OddJobName' => $_POST['OddJobName'],
'Description' => $_POST['Description'],
'DaysAvailable' => $daysavailable,
);
Delete_Oddjob ($Delete_Oddjob);
if(success){
header('Location: member.php?username='.$username);
exit ();
}
} else if (empty($errors) === false){
//otherwise output errors
echo output_errors($errors);
}
?>
<?php
$result = mysql_query("SELECT * FROM `oddjob` WHERE `MemberID` = $MemberID");
while($row = mysql_fetch_assoc($result))
{
echo"<table width='100%' border='1' cellspacing='0' cellpadding='5'>
<td width='50%'>
<table width='100%' cellspacing='17' cellpadding='0'>
<form action='' method ='post' enctype='multipart/form-data'>
<tr>
<td>
<input type='hidden' name='MemberID' id='MemberID' value= ". $MemberID .">
</td>
</tr>
<tr>
<td>
<input type='hidden' name='OddJobID' id='OddJobID' value= ". $row['OddJobID'] .">
</td>
</tr>
<tr>
<td width='35%'>
<p>Name of OddJob*:</p>
</td>
<td>
<input type='text' name='OddJobID' style='width:180px' value= ". $row['OddJobID'].">
</td>
</tr>
<tr>
<td width='35%'>
<p>Name of OddJob*:</p>
</td>
<td>
<input type='text' name='OddJobName' style='width:180px' value= ". $row['OddJobName'].">
</td>
</tr>
<tr>
<td>
<p>Description*:</p>
</td>
<td>
<div class='expandingArea'>
<pre><span></span><br></pre>
<textarea name='Description'>". $row['Description'] ."</textarea>
</div>
</td>
</tr>
<tr>
<td>
<p>Days Available(current week)*:</p>
<p>(hold Ctrl to select multiple)</p>
</td>
<td>
<select name='DaysAvailable[]' size='5' multiple='multiple' id='DaysAvailable[]'>
<option value='Monday'>Monday</option>
<option value='Tuesday'>Tuesday</option>
<option value='Wednesday'>Wednesday</option>
<option value='Thursday'>Thursday</option>
<option value='Friday'>Friday</option>
<option value='Saturday'>Saturday</option>
<option value='Sunday'>Sunday</option>
</select>
</td>
</td>
<tr>
<td>
<input type='checkbox' name='Delete' value= ". $row['OddJobID'] .">
</td>
</tr>
</table>
</table>
</table>
<input type='submit' name='Delete' value='Delete'>
</form> ";
}
?>
Function:
function Delete_Oddjob ($Delete_Oddjob){
//global $Add_Oddjob;
array_walk($Delete_Oddjob, 'array_sanitize');
mysql_query("DELETE FROM `oddjob` WHERE `OddJobID` = '".$_POST['OddJobID']."'") or die (mysql_error());
}
I don't understand how to make this work. At the moment when I select a check box and click the delete button the page seems to refresh but nothing else happens. Also If i try to echo out the query nothing is displayed.
echo "DELETE FROM `oddjob` WHERE `OddJobID` = '".$_POST['OddJobID']."'";
Any help would be great. Thank you.

You pretty much have the solution there.
Rename your Delete checkboxes to name="delete[]" that allows multiple checkboxes to be posted under the one name, then on the PHP side of things you can access these by saying:
if (isset($_POST['delete'])) {
foreach($_POST['delete'] as $oddjob) {
if (Delete_Oddjob($oddjob)) {
// success
} else {
// failure
}
}
}
Whenever the form is submitted and the delete option has been selected this will loop through all the checked checkboxes on the form and delete them using their ID.

Related

PHP method post cannot store data to database, no error generated

After searching for problems identical to mine and found no solution I decided to ask here.
I have 2 tables in 1 db, one is "produk" the other is "sparepart" both have the exact same number and name of columns.
I wrote the exact same code of HTML and PHP, just changed the table name so the data will be stored to their respective table.
the problem is the data from produk.php is stored in produk table but, the data from sparepart.php is not stored in sparepart table after query.
I tried checking for errors, but no error generated and instead it echoes "success".
please take a look at my simplified code :
HTML
<?php echo "<header><h3>TAMBAHKAN PRODUK SPAREPART</h3></header>
<form method=POST action='$aksi?module=sparepart&act=input' enctype='multipart/form-data'>
<div class='module_content'>
<table id='rounded-corner'>
<tr>
<td width=70>Nama Produk</td>
<td> : <input type=text name='nama_produk' size=60></td>
</tr>
<tr>
<td>Kategori</td>
<td> :
<select name='kategori'>
<option value=0 selected>- Pilih Kategori -</option>";
$tampil=mysql_query("SELECT * FROM kategori ORDER BY nama_kategori");
while($r=mysql_fetch_array($tampil)){
echo "<option value=$r[id_kategori]>$r[nama_kategori]</option>";
}
echo "</select>
</td>
</tr>
<tr>
<td>Kategori 2</td>
<td> :
<select name='kategori2'>
<option value=0 selected>- Pilih Kategori2 -</option>";
$tampil2=mysql_query("SELECT * FROM kategori2 ORDER BY nama_kategori2");
while($r2=mysql_fetch_array($tampil2)){
echo "<option value=$r2[id_kategori2]>$r2[nama_kategori2]</option>";
}
echo "</select>
</td>
</tr>
<tr>
<td>Harga </td>
<td> : <input type=text name='harga' size=10></td>
</tr>
<tr>
<td>Stok</td>
<td> : <input type=text name='stok' size=5></td>
</tr>
<tr>
<td>Diskon</td>
<td> : <input type=text name='diskon' size=5></td>
</tr>
<tr>
<td>Potongan</td>
<td> : <input type=tetxt name='potongan' size=10></td>
</tr>
<tr>
<td valign=top>Deskripsi</td>
<td> <textarea name='deskripsi' style='width: 600px; height: 350px;'></textarea></td>
</tr>
<tr>
<td>Gambar</td>
<td> : <input type=file name='fupload' size=40>
<br>Tipe gambar disarankan JPG/JPEG dan ukuran lebar maks: 400 px
</td>
</tr>
<tr>
<td colspan=2>
<input type=submit class='button' value=Simpan>
<input type=button class='button' value=Batal onclick=self.history.back()>
</td>
</tr>
</table>
</form>";?>
and the PHP :
<?php
$module=$_GET[module];
$act=$_GET[act];
$produk_seo = seo_title($_POST['nama_produk']);
if (!empty($lokasi_file)){
// Cek file type
if (($tipe_file =="image/jpeg" OR $tipe_file=="image/gif" OR
$tipe_file=="image/png" OR $tipe_file=="image/wbmp" )){
UploadImage($nama_file_unik);
$query1 ="INSERT INTO sparepart(nama_produk,
produk_seo,
id_kategori,
id_kategori2,
berat,
harga,
diskon,
stok,
deskripsi,
tgl_masuk,
potongan,
gambar)
VALUES('$_POST[nama_produk]',
'$produk_seo',
'$_POST[kategori]',
'$_POST[kategori2]',
'$_POST[berat]',
'$_POST[harga]',
'$_POST[diskon]',
'$_POST[stok]',
'$_POST[deskripsi]',
'$tgl_sekarang',
'$_POST[potongan]',
'$nama_file_unik')";
$sql = mysql_query($query1);
if (!sql) {
die('there is an error');
mysql_errno($sql).":".mysql_error($sql);
} else {
echo "success bro!";
}
}
else
{
$query2 = "INSERT INTO sparepart(nama_produk,
produk_seo,
id_kategori,
id_kategori2,
berat,
harga,
diskon
stok,
deskripsi,
potongan,
tgl_posting)
VALUES('$_POST[nama_produk]',
'$produk_seo',
'$_POST[kategori]',
'$_POST[kategori2]',
'$_POST[berat]',
'$_POST[harga]',
'$_POST[diskon]',
'$_POST[stok]',
'$_POST[deskripsi]',
'$_POST[potongan]',
'$tgl_sekarang')";
$sql=mysql_query($query2);
if(!sql) {
die('there is an error');
mysql_errno($sql).":".mysql_error($sql);
} else {
echo "success bro!";
}
}
I want to know why between the 2 same codes, only 1 works and the other does not echo any error but not working.
I am using mysqli_* in my real project. I just felt more comfortable using Mysql_* when writing this question so thank you for warning me about mysql_* being deprecated.
use the die() method at the end, thats why you are not getting the error.
if (!sql) {
/* die('there is an error'); */ // was like this before
echo mysql_errno($sql).":".mysql_error($sql);
die('there is an error'); // make it like this
}
$a=$_POST['kategori'];
$b=$_POST['kategori2'];
$query=mysql_query("INSERT INTO sparepart VALUES('$a','$b')");
if(!query)
{
die('there is an error');
}
else
{
echo "success bro!";
}
do Something like this note:- use '' in POST.

adding multiple rows in mysql

I have a big problem that somebody is attacking me by adding multiple rows into my db. Hes using the form I have on my website. I got about 2500 rows in my db and all rows were different. Its been generating by any script. Do you have any suggestions how I can fix it? this is my form I have on my website
<?php
if(isset($_POST['type'])) {$type = mysql_real_escape_string($_POST['type']);}
if(isset($_POST['ip'])) {$ip = mysql_real_escape_string($_POST['ip']);}
if(isset($_POST['port'])) {$port = mysql_real_escape_string($_POST['port']);}
$add_date = time();
if(isset($_POST['email'])) {$email = mysql_real_escape_string($_POST['email']);}
if(isset($_POST['web'])) {$web = mysql_real_escape_string($_POST['web']);}
if(isset($_POST['mod'])) {$mod = mysql_real_escape_string($_POST['mod']);}
echo "
<form action='#' method='post'>
<legend>Formulár pre pridanie serveru</legend>
<table>
<tr>
<td>
Hra:
</td>
<td>
<select name='type'>
<option value='cs16'>Counter Strike 1.6</option>
<option value='source'>Counter Strike Source</option>
<option value='csgo'>Counter Strike Global Offensive</option>
</select>
(vyberte hru)
</td>
</tr>
<tr>
<td>
Typ:
</td>
<td>
<select name='mod'>";
$modes = mysql_query("SELECT * FROM `lgsl_modes`") or die(mysql_error());
while($modes_names = mysql_fetch_array($modes))
{
echo '<option value="'.$modes_names['mod'].'">'.$modes_names['name'].'</option>';
}
echo "</select>
(vyberte herný mód)
</td>
</tr>
<tr>
<td>
IP serveru:
</td>
<td>
<input type='text' name='ip' value='' required>
(iba číslice a bodky)
</td>
</tr>
<tr>
<td>
Port serveru:
</td>
<td>
<input type='text' name='port' value='' required>
(iba číslice)
</td>
</tr>
<tr>
<td>
Web serveru:
</td>
<td>
<input type='text' name='web' value='' required>
(uvádzajte bez začiatočného http://)
</td>
</tr>
<tr>
<td>
Váš email:
</td>
<td>
<input type='text' name='email' value='' required>
(kontaktný email)
</td>
</tr>
<tr>
<td>
<input type='submit' name='odoslat' value='Odoslať'>
</td>
</tr>
</table>
</form>
";
if($ip) if(!preg_match("/^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$/",$ip)) $usermsgip="Ip adresa bola uvedená v zlom tvare.";
if($port) if(!preg_match("/^[0-9]{5}$/",$port)) $usermsgport="Port bol uvedený v zlom tvare.";
if($email) if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/",$email)) $usermsgemail="Email bol uvedený v zlom tvare.";
if($web) if(!preg_match("%^((https?://)|(www\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i" ,$web)) $usermsgweb="Web bol uvedený v zlom tvare.";
if(isset($_POST['odoslat']) && $usermsgip || $usermsgport || $usermsgemail || $usermsgweb) {
if($usermsgip) echo $usermsgip."<br>";
if($usermsgport) echo $usermsgport."<br>";
if($usermsgemail) echo $usermsgemail."<br>";
if($usermsgweb) echo $usermsgweb."<br>";
}
if(isset($_POST['odoslat']) && !$usermsgip && !$usermsgport && !$usermsgemail && !$usermsgweb) {
$kontrola = mysql_query("SELECT * FROM `lgsl` WHERE `ip`='".$ip."' AND `c_port`=".$port);
if(mysql_num_rows($kontrola)) {echo "Server už bol pridaný do banlistu.";}
else {
mysql_query("INSERT INTO `lgsl` (`type`, `ip`, `c_port`, `q_port`, `disabled`, `add_date`, `email`, `web`, `mod`)
VALUES ('$type', '$ip', '$port', '$port', '1', '$add_date', '$email', '$web', '$mod')");
echo 'Server bol úspešne odoslaný na schválenie.';
}
}
?>
I think you should rewrite the whole script using PDO. With Pdo you can avoid SQL-Injection in easy way. Here's a link where you can find that and all the web is full of guide and examples.
Anyway if you want to fix your script you can use Captcha to avoid automatic form submit and a library to sanitize input.
Here you find a simple captcha example and a good sanitize library.
You can whatch here some good tips to solve problems.
Hope this helps.

Access denied to database table for MySQL/PHP code

I am new to PHP and MySQL, but not coding in general. I am attempting to migrate an Access database into MySQL.
I get the following error after submitting my form information and trying to add a record to the table:
Access denied for user ''#'localhost' to database 'FltLogbook'
In order for the form to build, I access the database to pull out certain values for drop down menus. All of that works fine. After clicking the "Add Entry" button and using the Post method, the above error is shown.
I am very confused since previous queries ran just fine, but once I try to "add" the record, I get the error. The above error appears to be an anonymous connection. FWIW, the Username I connect with has all priviledges to the database. I have tried adding records with that username inside the form building portion of the code and was successful. You will see in the code below I have commented out my actual Insert code. I was troubleshooting data types and trying to simplify the insert command to eliminate other fields causing the error. The current insert command code works fine in the form building portion of the code, so I know I have the correct code, now I just to solve the connection issue.
After much searching on this site and google, most of the responses to the above error usually involve granting user permissions. I don't think that is the problem here since I can add a record inside the form building portion of the code. It appears I go from being an authenticated user to anonymous since no username is not passed in the error. I used connection_status() in both parts of the code and it returns 0 (Normal).
Any help is certainly appreciated. Cheers, Heed
Code:
$conn = mysqli_connect("localhost", $_POST[user], $_POST[password], "FltLogbook");
if ($_POST[op] != "add") {
//Form not shown, show it
$display="<h1>Add Logbook Entry</h1>";
$CnxSt = connection_status();
$display .= "Connection Status: $CnxSt<br><br>";
$display .= "
<form method=\"post\" action=\"$_SERVER[PHP_SELF]\">
<strong>Details:</strong>
<table border=\"1\" width=\"520\">
<tr>
<td><input type=\"checkbox\" name=\"Sim\">Simulator</td>
<td colspan=\"2\">SimType: <select name=\"SimType\">
<option value=\"\"> NA </option>
<option value=\"Miltary Visual\"> Military Visual </option>
<option value=\"Military Non-Visual\"> Military Non-Visual </option>
<option value=\"ATD\"> ATD </option>
<option value=\"FTD\"> FTD </option>
<option value=\"FFS\"> FFS </option></select></td>
</tr>
<tr>
<td>Date: <input type=\"date\" name=\"FltDate\"></td>
<td>Aircraft: <select name=\"Aircraft\">
<option selected=\"selected\" value=\"26\">C-172M</option>";
$AcftQuery="SELECT Aircraft.AirKey,Aircraft.Aircraft, Aircraft.ME, Aircraft.Complex, Aircraft.HighPerf
FROM Aircraft";
$AcftResult=mysqli_query($conn, $AcftQuery) or die ("Aircraft Query Failed");
While ($AcftRow=mysqli_fetch_array($AcftResult)) {
$AcftKey=$AcftRow['AirKey'];
$AcftAircraft=$AcftRow['Aircraft'];
$AcftME=$AcftRow['ME'];
$AcftComplex=$AcftRow['Complex'];
$AcftHP=$AcftRow['HighPerf'];
$display .= "<option value=\"$AcftKey\"> $AcftAircraft </option>";
}
$display .= "
</select>
</td>
<td>Aircraft ID: <input type=\"text\" name=\"ID\" size=\"8\"></td>
</tr>
<tr>
<td>From: <select name=\"From\">
<option selected=\"selected\" value=\"PVG\">PVG</option>";
$ArfldQuery="SELECT AirfieldID FROM Airfields ORDER BY AirfieldID";
$ArfldResult=mysqli_query($conn, $ArfldQuery) or die ("Airfield Query Failed");
While ($ArfldRow=mysqli_fetch_array($ArfldResult)) {
$Arfld=$ArfldRow['AirfieldID'];
$display .= "<option value=\"$Arfld\"> $Arfld </option>";
}
$display .= "
</select>
</td>
<td>To: <select name=\"To\">
<option selected=\"selected\" value=\"PVG\">PVG</option>";
$ArfldQuery="SELECT AirfieldID FROM Airfields ORDER BY AirfieldID";
$ArfldResult=mysqli_query($conn, $ArfldQuery) or die ("Airfield Query Failed");
While ($ArfldRow=mysqli_fetch_array($ArfldResult)) {
$Arfld=$ArfldRow['AirfieldID'];
$display .= "<option value=\"$Arfld\"> $Arfld </option>";
}
$display .= "
</select>
</td>
<td>Leg: <select name=\"Leg\">
<option value=\"1\">1</option>
<option value=\"2\">2</option>
<option value=\"3\">3</option>
<option value=\"4\">4</option>
<option value=\"5\">5</option>
<option value=\"6\">6</option>
</select>
</td>
</tr>
</table><br>
<strong>Flight Time Info:</strong>
<table border=\"1\" width=\"520\">
<tr>
<td>TPT: <input type=\"text\" name=\"TPT\" size=\"4\"></td>
<td>PIC: <input type=\"text\" name=\"PIC\" size=\"4\"></td>
<td>SIC: <input type=\"text\" name=\"SIC\" value=\"0.0\" size=\"4\"></td>
</tr>
<tr>
<td>Solo: <input type=\"text\" name=\"Solo\" value=\"0.0\" size=\"4\"></td>
<td colspan=\"2\">Dual Received: <input type=\"text\" name=\"Dual\" value=\"0.0\" size=\"4\"></td>
</tr>
<tr>
<td>Cross Country: <input type=\"text\" name=\"XC\" value=\"0.0\" size=\"4\"></td>
<td><input type=\"checkbox\" name=\"FARXCntry\" size=\"4\">FAR X-Cntry</td>
<td><input type=\"checkbox\" name=\"ATPXCntry\" size=\"4\">ATP X-Cntry</td>
</tr>
<tr>
<td>Single Engine: <input type=\"text\" name=\"SE\" size=\"4\"></td>
<td>Multiengine: <input type=\"text\" name=\"ME\" size=\"4\"></td>
<td>Night: <input type=\"text\" name=\"NT\" value=\"0.0\" size=\"4\"></td>
</tr>
<tr>
<td>Complex: <input type=\"text\" name=\"Complex\" value=\"0.0\" size=\"4\"></td>
<td colspan=\"2\">High Performance: <input type=\"text\" name=\"HP\" value=\"0.0\" size=\"4\"></td>
</tr>
<tr>
<td>Instrument: <input type=\"text\" name=\"Inst\" value=\"0.0\" size=\"4\"></td>
<td colspan=\"2\">Sim Instrument: <input type=\"text\" name=\"SimInst\" value=\"0.0\" size=\"4\"></td>
</tr>
<tr>
<td>Instructor: <input type=\"text\" name=\"Instructor\" value=\"0.0\" size=\"4\"></td>
<td>Pre-Post: <input type=\"text\" name=\"PrePost\" value=\"0.0\" size=\"4\"></td>
<td>Ground: <input type=\"text\" name=\"Ground\" value=\"0.0\" size=\"4\"></td>
</tr>
</table><br>
<strong>Actual Approaches:</strong>
<table border=\"1\" width=\"520\">
<tr>
<td>Precision: <input type=\"text\" name=\"PrecAct\" value=\"0\" size=\"3\"></td>
<td>Non-Precision: <input type=\"text\" name=\"NonPrecAct\" value=\"0\" size=\"3\"></td>
</tr>
</table><br>
<strong>Simulated Approaches:</strong>
<table border=\"1\" width=\"520\">
<tr>
<td>Precision: <input type=\"text\" name=\"PrecSim\" value=\"0\" size=\"3\"></td>
<td>Non-Precision: <input type=\"text\" name=\"NonPrecSim\" value=\"0\" size=\"3\"></td>
</tr>
</table><br>
<strong>Landings:</strong>
<table border=\"1\" width=\"520\">
<tr>
<td>Day Landings: <input type=\"text\" name=\"DayLdg\" size=\"3\"></td>
<td>Night Landings: <input type=\"text\" name=\"NtLdg\" size=\"3\"></td>
</tr>
</table><br>
<strong>Remarks:</strong><br>
<textarea name=\"Remarks\" rows=\"5\" cols=\"70\"></textarea>
<input type=\"hidden\" name=\"op\" value=\"add\">
<p><input type=\"submit\" name=\"submit\" value=\"Add Entry\"></p>
</FORM>";
} else if ($_POST[op] == "add") {
if ($_POST[Sim] == "") {
$_POST[Sim] = "0";
} else {
$_POST[Sim] = "1";
}
if ($_POST[FARXCntry] == "") {
$_POST[FARXCntry] = "0";
} else {
$_POST[FARXCntry] = "1";
}
if ($_POST[ATPXCntry] == "") {
$_POST[ATPXCntry] = "0";
} else {
$_POST[ATPXCntry] = "1";
}
// $add_flt = "INSERT INTO FlightData (Date, MakeModel, AircraftID, Simulator, SimType, AfldFrom, AfldTo,
// Leg, TPT, PIC, SIC, Solo, Dual, Night, XCntry, SE, ME, Complex, HighPerf, Inst_Act, Inst_Sim,
// Instructor, PrePost, Ground, Prec_Act, Prec_Sim, NonPrec_Act, NonPrec_Sim, DCL, NCL,
// FAR_XCntry, ATP_XCntry, Remarks)
// VALUES ('$_POST[FltDate]', '$_POST[Aircraft]', '$_POST[ID],$_POST[Sim]', '$_POST[SimType]', '$_POST[From]',
// '$_POST[To]', '$_POST[Leg]', '$_POST[TPT]', '$_POST[PIC]', '$_POST[SIC]', '$_POST[Solo]', '$_POST[Dual]',
// '$_POST[NT]', '$_POST[XC]', '$_POST[SE]', '$_POST[ME]', '$_POST[Complex]', '$_POST[HP]', '$_POST[Inst]',
// '$_POST[SimInst]', '$_POST[Instructor]', '$_POST[PrePost]', '$_POST[Ground]', '$_POST[PrecAct]',
// '$_POST[PrecSim]', '$_POST[NonPrecAct]', '$_POST[NonPreSim]', '$_POST[DayLdg]', '$_POST[NtLdg]',
// '$_POST[FARXCntry]', '$_POST[ATPXCntry]', '$_POST[Remarks]')";
$add_flt = "INSERT INTO FlightData (Date, MakeModel) VALUES ('$_POST[FltDate]', '$_POST[Aircraft]')";
mysqli_query($conn, $add_flt) or die('Error: '. mysqli_connect_error());
$display = "<h1>Entry Added</h1>
<p>Your entry was added.</p><br>
<p>$_POST[FltDate] | $_POST[Aircraft] </p>";
// $CnxSt = connection_status();
// $display .= "Connection Status: $CnxSt<br><br>";
// $display .= "$user / $pwd<br>$add_flt<br>";
// $display .= "$_POST[FltDate] / $_POST[Aircraft] / $_POST[ID] / $_POST[Sim] / $_POST[FARXCntry] / $_POST[ATPXCntry]";
}
?>
<html>
<head>
<title>Add Logbook Entry></title>
</head>
<body>
<?php echo $display; ?>
</body>
</html>
You must check your mysql username and password on line 1
if username="root" & password is null then
$conn = mysqli_connect("localhost", "root", "", "FltLogbook");

Data some is errased when update button is pressed

Please, I am having a problem when updating data in the database through a form. When ever I press the Update button to submit any changes made to a record, all the data in the mysql fields corresponding to drop list controls is errased. I do not know what is causing this problem. Here is the code:
<?php
//include database connection
include 'db_connect.php';
// get value of object id that was sent from address bar
$c_id = $_GET['c_id'];
//check any user action
$action = isset( $_POST['action'] ) ? $_POST['action'] : "";
if($action == "update"){ //if the user hit the submit button
//write our update query
//$mysqli->real_escape_string() function helps us prevent attacks such as SQL injection
$query = "UPDATE collections
SET
ctitle = '".$mysqli->real_escape_string($_POST['ctitle'])."',
csubject = '".$mysqli->real_escape_string($_POST['csubject'])."',
creference = '".$mysqli->real_escape_string($_POST['creference'])."',
cyear = '".$mysqli->real_escape_string($_POST['cyear'])."',
cobjecttype = '".$mysqli->real_escape_string($_POST['cobjecttype'])."',
cmaterial = '".$mysqli->real_escape_string($_POST['cmaterial'])."',
ctechnic = '".$mysqli->real_escape_string($_POST['ctechnic'])."',
cwidth = '".$mysqli->real_escape_string($_POST['cwidth'])."',
cheight = '".$mysqli->real_escape_string($_POST['cheight'])."',
cperiod = '".$mysqli->real_escape_string($_POST['cperiod'])."',
cmarkings = '".$mysqli->real_escape_string($_POST['cmarkings'])."',
cdescription = '".$mysqli->real_escape_string($_POST['cdescription'])."',
csource = '".$mysqli->real_escape_string($_POST['csource'])."',
cartist = '".$mysqli->real_escape_string($_POST['cartist'])."'
where c_id='".$mysqli->real_escape_string($_REQUEST['c_id'])."'";
//execute the query
if( $mysqli->query($query) ) {
//if updating the record was successful
echo "The record was updated.";
}else{
//if unable to update new record
echo "Database Error: Unable to update record.";
}
}
//select the specific database record to update
$query = "SELECT c_id, ctitle, csubject, creference, cyear, cobjecttype, cmaterial, ctechnic, cwidth, cheight, cperiod, cmarkings, cdescription, csource, cartist, cfilename
FROM collections
WHERE c_id='".$mysqli->real_escape_string($_REQUEST['c_id'])."'
limit 0,1";
//execute the query
$result = $mysqli->query( $query );
//get the result
$row = $result->fetch_assoc();
//assign the result to certain variable so our html form will be filled up with values
$c_id = $row['c_id'];
$ctitle = $row['ctitle'];
$csubject = $row['csubject'];
$creference = $row['creference'];
$cyear = $row['cyear'];
$cobjecttype = $row['cobjecttype'];
$cmaterial = $row['cmaterial'];
$ctechnic = $row['ctechnic'];
$cwidth = $row['cwidth'];
$cheight = $row['cheight'];
$cperiod = $row['cperiod'];
$cmarkings = $row['cmarkings'];
$cdescription = $row['cdescription'];
$csource = $row['csource'];
$cartist = $row['cartist'];
$cfilename = $row['cfilename'];
?>
<!--we have our html form here where new object information will be entered-->
<table align=left>
<tr>
<td> <?php echo '<img src="./images/'.$cfilename.'" width="300" height="400" />'; ?> </td>
</tr>
<table>
<form action='#' method='post' border='0'>
<table>
<tr>
<td>TITLE</td>
<td><input type='text' name='ctitle' value='<?php echo $ctitle; ?>' /></td>
</tr>
<tr>
<td>SUBJECT</td>
<td><input type='text' name='csubject' value='<?php echo $csubject; ?>' /></td>
</tr>
<tr>
<td>REFERENCE No.</td>
<td><input type='text' name='creference' value='<?php echo $creference; ?>' /></td>
</tr>
<tr>
<td>YEAR</td>
<td><input type='text' name='cyear' value='<?php echo $cyear; ?>' /></td>
<tr><td>OBJECT TYPE</td>
<td>
<select name="cobjecttype" id="cobjecttype" tabindex="">
<option value="">---Select object type---</option>
<option value="ceramic">Ceramic</option>
<option value="clock">Clock</option>
<option value="gold">Gold and silverware</option>
<option value="mask">Mask</option>
<option value="painting">Painting</option>
<option value="sculpture">Sculpture</option>
<option value="tapestry">Tapestry</option>
</select>
</td></tr>
<tr><td>MATERIAL USED</td>
<td>
<select name="cmaterial" id="cmaterial" tabindex="" >
<option value="">---Select Material---</option>
<option value="brass">Brass</option>
<option value="oil">Oil</option>
<option value="wood">Wood</option>
<option value="carved">Canvas/Cotton/Fabric/Linen/Wool</option>
</select>
</td></tr>
<tr><td>TECHNIC</td>
<td>
<select name="ctechnic" id="ctechnic" tabindex="7" >
<option value="">---Select Technic---</option>
<option value="cast">Cast</option>
<option value="carved">Carved</option>
<option value="etched">Etched</option>
</select>
</td></tr>
<tr>
<td>WIDTH</td>
<td width="100"><input name="cwidth" type="text" id="cwidth" value="<?php echo $cwidth; ?>" size="10"></td>
</tr>
<tr>
<td>HEIGHT</td>
<td width="100"><input name="cheight" type="text" id="cheight" value="<?php echo $cheight; ?>" size="10"></td>
</tr>
<tr>
<td>PERIOD</td>
<td width="100"><input name="cperiod" type="text" id="cperiod" value="<?php echo $cperiod; ?>" size="30"></td>
</tr>
<tr>
<td>MARKINGS</td>
<td width="100"><input name="cmarkings" type="text" id="cmarkings" value="<?php echo $cmarkings; ?>" size="30"></td>
</tr>
<tr>
<td>DESCRIPTION</td>
<td width="400"><textarea name="cdescription" rows="2" cols="50" id="cdescription" value="<?php echo $cdescription; ?>"></textarea></td></tr>
<tr>
<td>SOURCE</td>
<td width="100"><input name="csource" type="text" id="csource" value="<?php echo $csource; ?>" size="30"></td>
</tr>
<tr>
<td>ARTIST</td>
<td width="100"><input name="cartist" type="text" id="cartist" value="<?php echo $cartist; ?>" size="30"></td>
</tr>
<td></td>
<td>
<!-- so that we could identify what record is to be updated -->
<input type='hidden' name='c_id' value='<?php echo $c_id ?>' />
<!-- we will set the action to update -->
<input type='hidden' name='action' value='update' />
<input type='submit' value='Save' />
<a href='gallery.php'>Back to display page</a>
</td>
</tr>
</table>
</form>
Can someone help to identify what the problem is?
Such problem occur when you dont validate your POST data correctly. In your code, you are updating your records directly, by using mysql_real_escape_string($variable). But although this might fix some security issues will not validated every data if it is present or not.
Validate your variables to be present and hold data before updating to the query.
you post a form with the method POST, but get the c_id with $_GET
change it to $_POST['c_id'] or $_REQUEST['c_id'] ...

Pass back values to form to populate it? (lots of values)

I need to pass back a large string of results to a form, so that the form can read those results from the URL and then populate the form with them. Problem is, the link ends up being:
&key=value&key=value ... until it can't process anymore (I assume a URL has a length limit?) resulting in my form not being able to fully populate. I need another way to pass values back to my form file.
VIEW.php file (basically just a table of values right as they are from the database, with the first column "id" being a link. When I click on "id", it goes back to my add.php(form page) and populates the form with the data matching that id)
<table border="0" cellpadding="0" cellspacing="0" id="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>MANUFACTURER</th>
<th>MODEL</th>
<th>DESCRIPTION</th>
<th>ON HAND</th>
<th>REORDER</th>
<th>COST</th>
<th>PRICE</th>
<th>SALE</th>
<th>DISCOUNT</th>
<th>DELETED</th>
<th></th>
</tr>
</thead>
<tbody>
<?php } ?>
<?php
// loop to fetch data
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>
<a href='molszewski1_a2_add.php'>$row[id]</a></td>";
echo "<td>$row[name]</td>";
echo "<td>$row[manufac]</td>";
echo "<td>$row[model]</td>";
echo "<td>$row[descrip]</td>";
echo "<td>$row[onhand]</td>";
echo "<td>$row[reorder]</td>";
echo "<td>$row[cost]</td>";
echo "<td>$row[price]</td>";
echo "<td>$row[sale]</td>";
echo "<td>$row[discont]</td>";
echo "<td>$row[deleted]</td>";
$status = "$row[deleted]";
echo "<td><a href='molszewski1_a2_delete.php?id=$row[id]&flag=$status&sort=$sort'>";
$status = "$row[deleted]";
if ($status == 'n') {
$flag = "restore";
echo "delete";
} else if ( $status == 'y') {
$flag = "delete";
echo "restore";
}
echo "</a></td>";
echo "</tr>";
} ?>
<?php { ?>
</tbody>
</table>
ADD.php (form page where the form is supposed to fetch the data and populate it)
<?php
// If no form has been submitted, present form
if (empty($_GET))
{
add_form();
}
// if a form has been submitted
else
{
// if form_validity() == 1, proceed to connect
if (form_validity() == 1)
{
// connect to mysql + database
connect();
$saleItem = "n";
$discountItem = "n";
if( array_key_exists( 'saleItem', $_GET ) && $_GET['saleItem'] == 'y' )
{ $saleItem = "y"; }
if( array_key_exists( 'discountItem', $_GET ) && $_GET['discountItem'] == 'y' )
{ $discountItem = "y"; }
// get values from form, insert into database
$sql=("INSERT INTO inventory (name,
manufac,
model,
descrip,
onhand,
reorder,
cost,
price,
sale,
discont,
deleted)
VALUES ('$_GET[itemName]',
'$_GET[manufacturer]',
'$_GET[model]',
'$_GET[description]',
'$_GET[numberOnHand]',
'$_GET[reorderLevel]',
'$_GET[cost]',
'$_GET[sellingPrice]',
'$saleItem',
'$discountItem', 'n')");
// if the query doesn't work, display error message
if (!(mysql_query($sql))) { die ("could not query: " . mysql_error()); }
add_form();
// redirect to view.php after form submission
// use php instead
echo "<meta http-equiv='REFRESH' content='0;url=molszewski1_a2_view.php'>";
}
else
{
// if form is not valid (form_validity returns 0), display error messages
add_form();
}
}
?>
FUNCTIONS.php (all my functions for stuff like the form)
<?php function page_navigation(){ ?>
<div class="center">
<input type="button" value="ADD" />
<input type="button" value="VIEW" />
<input type="button" value="VIEW DELETED" />
<input type="button" value="VIEW ACTIVE" />
<br />
<br />
</div>
<?php } ?>
<?php function add_form() { ?>
<form action="molszewski1_a2_add.php" method="get" id="form">
<table width="529px">
<tr>
<td>ITEM NAME</td>
<td><input name="itemName" size="30" type="text" value="<?php echo $_GET["itemName"] ?>"/></td>
</tr>
<tr>
<td>MANUFACTURER</td>
<td><input name="manufacturer" size="30" type="text" value="<?php echo $_GET["manufacturer"] ?>"/></td>
</tr>
<tr>
<td>MODEL</td>
<td><input name="model" size="30" type="text" value="<?php echo $_GET["model"] ?>"/></td>
</tr>
<tr>
<td>DESCRIPTION</td>
<td><textarea name="description" rows="3" cols="20"><?php echo $_GET["description"] ?></textarea></td>
</tr>
<tr>
<td>ON HAND</td>
<td><input name="numberOnHand" size="30" type="text" value="<?php echo $_GET["numberOnHand"] ?>"/></td>
</tr>
<tr>
<td>REORDER LEVEL</td>
<td><input name="reorderLevel" size="30" type="text" value="<?php echo $_GET["reorderLevel"] ?>"/></td>
</tr>
<tr>
<td>COST</td>
<td><input name="cost" size="30" type="text" value="<?php echo $_GET["cost"] ?>"/></td>
</tr>
<tr>
<td>SELLING PRICE</td>
<td><input name="sellingPrice" size="30" type="text" value="<?php echo $_GET["sellingPrice"] ?>"/></td>
</tr>
<tr>
<td>SALE ITEM</td>
<td>
<input type="checkbox" name="saleItem" value="y" <?php if( isset( $_GET['saleItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td>DISCOUNTED ITEM</td>
<td>
<input type="checkbox" name="discountItem" value="y" <?php if( isset( $_GET['discountItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="save" name="submit" id="submit" /></td>
</tr>
</table>
</form>
<?php } ?>
Use method="post" and $_POST (instead of $_GET).
POST requests can be much larger than GET requests as GET requests are limited by the maximum length of a URL. POST requests are limited by the size of the max_post_size ini-value which is usually a few megabytes.

Categories