User value used instead of PHP value in textbox - php

I have a webpage thats purpose is to edit entries from a database. Its populated using PHP but i need the user to be able to change the value in these and update the database with the new value.
The problem im having is when i POST the data back from the form to the data base, the new information is NOT used, instead the PHP is. How do i fix this?
Each dropdown, text box and text field is populated from the text box using php:
<div class="col-lg-6">
<div class="form-group">
<label>Version</label>
<input type="text" class="form-control" name="forensic_tool_version" placeholder="Version" value="<?php
$session_name = $_SESSION['first_name']." ".$_SESSION['surname'];
$sql_query = "SELECT fi_forensic_tool_ver FROM asset_tracker WHERE asset_id = ? LIMIT 1";
$db_field = "fi_forensic_tool_ver";
$asset_id = $_GET['assetid'];
get_db_field($mysqli, $sql_query, $db_field, $asset_id, $session_name);
?>"/>
</div>
The get_db_field just gets the data and echos it to screen. This all works.
The user will then change one or more fields and click submit, where the following update will occur:
<!-- DATABASE INPUT - Input form elements into database -->
<?php
if(!empty($_GET['requestor']) ){
$asset_id = $_GET['assetid'];
$add_requestor = $_GET['requestor'];
$add_kc_number = $_GET['kc_number'];
$add_project_name = $_GET['project_name'];
$add_custodian = $_GET['custodian'];
$add_business_area = $_GET['business_area'];
$add_task = $_GET['task'];
$add_utl_reference = $_GET['utl_reference'];
$add_purchase_price_value = $_GET['purchase_price_value'];
$add_request_date = $_GET['request_date'];
$add_return_date = $_GET['return_date'];
$add_device_type = $_GET['device_type'];
$add_manufacturer = $_GET['manufacturer'];
$add_username = $_GET['username'];
$add_model = $_GET['model'];
$add_pinOrPassword = $_GET['pinOrPassword'];
$add_vf_asset_num = $_GET['vf_asset_num'];
$add_serial_num = $_GET['serial_num'];
$add_imei = $_GET['imei'];
$add_forensic_tool = $_GET['forensic_tool'];
$add_forensic_tool_version = $_GET['forensic_tool_version'];
$add_bitlocker_key = $_GET['bitlocker_key'];
$add_image_verified = $_GET['image_verified'];
$add_case_notes = $_GET['case_notes'];
$add_case_photos = $_GET['case_photos'];
if($query = $mysqli->prepare("UPDATE asset_tracker SET ci_requesting_employee=?, ci_kc=?, ci_project_name=?, ci_custodian=?, ci_business_area=?, ci_task=?, ci_utl_reference=?, ci_purchase_price_value=?, ci_date_requested=?, ci_date_returned=?, di_type=?, di_manufacturer=?, di_model=?, di_username=?, di_password=?, di_vf_asset=?, di_serial=?, di_imei=?, fi_forensic_tool=?, fi_forensic_tool_ver=?, fi_bitlocker_key=?, fi_image_verified=?, cn_notes=?, cn_photos=? WHERE asset_id = ? LIMIT 1")){
$query->bind_param('ssssssssssssssssssssssssi', $add_requestor, $add_kc_number, $add_project_name, $add_custodian, $add_business_area, $add_task, $add_utl_reference, $add_purchase_price_value, $add_request_date, $add_return_date, $add_device_type, $add_manufacturer, $add_username, $add_model, $add_pinOrPassword, $add_vf_asset_num, $add_serial_num, $add_imei, $add_forensic_tool, $add_forensic_tool_version, $add_bitlocker_key, $add_image_verified, $add_case_notes, $add_case_photos, $asset_id);
$query->execute();
$query->close();
echo "<script type='text/javascript'>alert('Asset updated Successfully');</script>";
}else{
echo "<script type='text/javascript'>alert('Cannot access database');</script>";
}
}else{
//echo "<script type='text/javascript'>alert('Post not set');</script>";
}
?>
Any help on this would be much appreciated!
Thanks!

Related

Updating and deleting from a data table, warning undefined array key

I have been following a lesson on how to make an admin page. I got all the information out of my database to a table on the page. I have an update button and when I change the information and press the button I receive this error: Warning: undefined array key "WebID" in ..\Update.php on line 3
From my search online everyone is trying to change the code so that if array key does not exist: return null. I tried that and the error does not appear no more, but the table does not change.
Any thoughts?
This is the code:
<?php
require_once("DB/DB.php");
$SearchQueryParameter = $_GET["WebID"];
if (isset($_POST["Update"])) {
$Ename = $_POST["Ename"];
$Eid = $_POST["Eid"];
$Erank = $_POST["Erank"];
$Eemail = $_POST["Eemail"];
$Edate = $_POST["Edate"];
$Epassword = $_POST["Epassword"];
$Specialisms = $_POST["Specialisms"];
global $ConnectingDB;
$sql ="UPDATE emp_data SET Ename='$Ename', Eid='$Eid', Erank='$Erank', Eemail='$Eemail', Edate='$Edate', Epassword='$Epassword',
Specialisms='$Specialisms' WHERE WebID='$SearchQueryParameter'";
$Execute = $ConnectingDB->query($sql);
if ($Execute) {
echo '<script>window.open("adminpage.php?WebID=Recored Updated","_self")</script>';
}
}
?>
<?php
<?php
global $ConnectingDB;
$sql = "SELECT * FROM emp_data WHERE WebID='$SearchQueryParameter'";
$stmt = $ConnectingDB->query($sql);
while ($DataRows = $stmt->fetch()) {
$WebID = $DataRows["WebID"];
$Ename = $DataRows["Ename"];
$Eid = $DataRows["Eid"];
$Erank = $DataRows["Erank"];
$Eemail = $DataRows["Eemail"];
$Edate = $DataRows["Edate"];
$Epassword = $DataRows["Epassword"];
$Specialisms = $DataRows["Specialisms"];
}
?>
Html file used to update:
<form id="UpdateForm" method="post" action="Update.php?WebID<?php echo $SearchQueryParameter; ?>">
<div class="form-group">
<button type="submit" name="Update" class="form-control-submit-button">Update</button>
</div>
you have to write the form action like this.. you missed the = sign
action="Update.php?WebID=<?php echo $SearchQueryParameter; ?>"
<form id="UpdateForm" method="post" action="Update.php?WebID=<?php echo $SearchQueryParameter; ?>">
You missed the = sign, in the url

how can I insert data using a form into a database using PHP

I am trying to insert data using a form into my database, but I see the data being shown on the URL tab instead of my database table, here's my code can anyone tell me what is wrong with it please
<?php
if(isset($_POST['submit'])){
$Coupon_title = $_POST['Coupon_title'];
$Coupon_cat = $_POST['Coupon_cat'];
$Coupon_code = $_POST['Coupon_code'];
$Coupon_value = $_POST['Coupon_value'];
$Coupon_status = $_POST['Coupon_status'];
$Coupon_date = $_POST['Coupon_date'];
$Coupon_limit = $_POST['Coupon_limit'];
$Coupon_used = $_POST['Coupon_used'];
$Coupon_price = $_POST['Coupon_price'];
$Coupon_image = $_FILES['Coupon_image']['name'];
$temp_name = $_FILES['Coupon_image']['temp_name'];
move_uploaded_file($temp_name,"Coupon_image/$Coupon_image");
$insert_coupon = "INSERT INTO coupon_master (Coupon_title,Coupon_cat,Coupon_code,Coupon_value,Coupon_status,Coupon_date,Coupon_limit,Coupon_used,Coupon_price) values('$Coupon_title','$Coupon_cat','$Coupon_code','$Coupon_value','$Coupon_status',NOW(),'$Coupon_limit','$Coupon_used','$Coupon_price',)";
if($run_coupon){
echo "<script>alert('Product has been inserted successfully')</script>";
echo "<script>window.open('insert_coupons.php','_self')</script>";
}
}
?>

Can't update form data

I am trying to edit form data by displaying the previous saved data on the form and then update it. It shows the data on the form which is saved in database but when i enter the new data it does not get the id of the row. I echo the update query, it shows the changed values but it shows id equals to empty. Here is my code for edit record and update; Edit record is working but update isn't:
<?php
include('connection.php');
$id = '';
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
$udfname = mysql_real_escape_string($_POST["udfname"]);
$udlname = mysql_real_escape_string($_POST["udlname"]);
$udpwd = mysql_real_escape_string($_POST["udpwd"]);
$udeml = mysql_real_escape_string($_POST["udeml"]);
$udnum = mysql_real_escape_string($_POST["udnum"]);
$query="UPDATE form
SET fname = '$udfname', lname = '$udlname', pwd = '$udpwd', eml = '$udeml', num = '$udnum'
WHERE id='$id'";
$res= mysql_query($query);
if($res){
echo "<p> Record Updated<p>";
}else{
echo "Problem updating record. MY SQL Error: " . mysql_error();
}
?>
Form for editing record:
<?php
include('connection.php');
$id = (int)$_GET['id'];
$query = mysql_query("SELECT * FROM form WHERE id = '$id'") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
echo "";
$fname = $row['fname'];
$lname = $row['lname'];
$pwd = $row['pwd'];
$eml = $row['eml'];
$num = $row['num'];
}
?>
<html>
<head>
<title>Edit</title>
<script>
'
'
Jquery code here
'
'
</script>
</head>
<body>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?=$id;?>">
First Name: <input type="text" name="udfname" value="<?=$fname;?>"><br>
Last Name: <input type="text" name="udlname" value="<?=$lname?>"><br>
Password: <input type="text" name="udpwd" value="<?=$pwd?>"><br>
Email: <input type="text" name="udeml" value="<?=$eml?>"><br>
Contact Number: <input type="text" name="udnum" value="<?=$num?>"><br>
<input type="Submit">
</form>
</body>
</html>
At update time your form is submitted using POST request. So you need to get ID using POST method. So to get ID of hidden field change your code as below:
$id = '';
if( isset( $_POST['ID'])) {
$id = $_POST['ID'];
}
Please try below code
if( isset( $_POST['id']) && $_POST['id']!=null) {
$id = $_POST['id'];
}
Dear i think the problem with your method you are sending the data using post method and its very simple instead of this code
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
write
if( isset( $_POST['id'])) {
$id = $_POST['id'];
}
and one more thing that is you are using the mysql deprecated function for database kindly use the pdo for this or new mysqli functions.

Form does not go to action page on submit

Edit 2: I traced the code through the php, and realized that it was a faulty header that was causing it to bounce back. I've fixed the header and now the form behaves as it should. Thanks everyone for your help.
EDIT: I noticed the form is quickly refreshing when I submit, so I think it is going to the action page (createlist.php) and immediately bouncing back, so there must be some issue there. Here is the code for createlist.php:
<?php
if (!isset($_SESSION)) {
session_start();
}
if (!defined(__DIR__)) {
define(__DIR__, dirname(__FILE__));
}
require_once(__DIR__.'/../config.php');
//Connect to server and select database.
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE) or die('Cannot connect to server');
//mysql_select_db(DB_DATABASE) or die('Cannot select database');
$tbl_name = 'lists'; //Table name
//Retreive data from form
$listname = $_POST['listName'];
$admin_id = $_SESSION['SESS_MEMBER_ID'];
$listtype = 'list';
//Create listname session variable for catinit.php
$_SESSION['listname'] = $listname;
//Insert new row
$sql = "INSERT INTO $tbl_name(admin_id, listname, listtype) VALUES ('$admin_id', '$listname', '$listtype')";
$result = mysqli_query($link, $sql);
if ($result) {
header("location: catinit.php");
} else {
die("Could not create list");
}
//mysql_close();
?>
I have 2 forms on a page, and while it was working before, since adding the backend handling of the information it has broken. Now when I submit either of the forms on the page nothing happens, it does not even attempt to load the action pages. I am completely lost as to what is stopping it from submitting, as everything looks like its working.
<h1>Create a New List</h1>
<form action = "createlist.php" method = "POST" id = "formId" onsubmit = "formValidate(0, 0, 0, 1, 'formId', 'submitError', event)">
<p>List Name:
<input type = "text" id = "listName" name = "listName" placeholder = "New List" onblur = "listNameValidate('listName','errorName1')" required><span class = "error" id = "errorName1"></span></p>
</form>
<h2>Categories</h2>
<ul class = "catList" id = "list">
<table>
<?php
$cats = array('Produce', 'Meat/Dairy', 'Baked Goods', 'Dry/Canned Goods', 'Household Items');
//Check to see if Session version of array has different values
if (isset($_SESSION['catArray']) && $_SESSION['catArray'] != $cats) {
$cats = $_SESSION['catArray'];
} else {
$_SESSION['catArray'] = $cats;
}
foreach ($cats as $cat) {
$index = array_search($cat, $cats);
echo '<tr><td><li>'.$cat.'</li></td><td> Remove</td></tr>';
}
?>
</table>
</ul>
New Category: <br>
<form action = "addcat.php" method = "POST" id = "addcat">
<input type = "text" id = "newCategory" name = "newCat" placeholder = "Category name" onblur = "listNameValidate('newCategory','errorName2')">
<input type = "hidden" name = "catArray" value = "<?php echo htmlentities(serialize($cats)); ?>" >
<input type = "submit" value= "Add" class = "add"><span class = "error" id = "errorName2"></span>
</form>
<h2>Invite Members</h2>
Add a new Member: <br>
<input type = "email" id = "email" name = "Email" placeholder = "Email Address" onblur = "emailValidate('email', 'errorEmail')">
<input type = "button" value = "Add" class = "add" ><span class = "error" id = "errorEmail"></span>
<p><input type = "submit" form = "formId" value = "Create"></p>
<p class = "submitError" id = "submitError"></p>

Have 4 'ands' in a select statement

I have a search function on my website with 4 checkboxes. These are then pasted to the next page where I want to find all products which match the criteria of the check boxes.
As I have 4 check boxes I want to use 4 'ands' but I believe 3 is the max (?)
How can I get around this so it searches to see if all products are matched?
HTML Form
<div id = "search">
<form name = search action = "search.php" method = "POST">
<p class = "big"> Refine Menu </p>
<hr>
<input type = "text" name = "search" placeholder = "Search for an item" size = "12">
<input type = "submit" value = "Go">
<br><br>
<input type = "checkbox" name = "vegetarian"> Vegetarian
<br><input type = "checkbox" name = "vegan"> Vegan
<br><input type = "checkbox" name = "coeliac"> Coeliac
<br><input type = "checkbox" name = "nutFree"> Nut free
</form>
</div>
PHP
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = NULL;
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = NULL;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = NULL;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = NULL;
}
$sql = "SELECT * FROM products WHERE vegan = '$vegan' and nutFree = '$nutFree' and vegetarian = '$vegetarian' and coeliac = '$coeliac'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
I've tried a number of different thing but I don't know the correct syntax for the sql.
NOTE: In my database whether it meets the requierment on it is saved as either a 1 or 0 that is why I changed it from 'on' or 'off'
Rather than a large, unmaintainable chain of if statements, you might consider something similar to the following, which will dynamically build up your query depending on which of your required fields have been checked in your form:
<?php
$search_fields = array( 'vegetarian', 'vegan', 'nutFree', 'coeliac', ...);
$ands = array( '1' => '1');
foreach($search_fields as $req)
{
if(isset($_POST[$req]) && $_POST[$req] != '')
{
$ands[$req] = "$req = '1'";
}
}
$and_part = implode(" AND ", $ands);
$query = "select .... from ... WHERE $and_part ... ";
?>
I managed to solve my problem. I was mistaken when I posted the question because the reason I thought my sql statement wasn't working was because there were too many ands and I didn't see that rather my sql didn't do what I thought it should.
Here is what I changed it to or it has set values or the check boxes ticked but always the ones which aren't to be either or.
Thanks for everyone's help!
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = " ";
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = " " ;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = " " ;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = " ";
}
$sql = "SELECT * FROM products WHERE (vegan = '$vegan' or vegan = 1 xor 0) and (nutFree = '$nutFree' or nutFree = 1 xor 0) and (vegetarian = '$vegetarian' or vegetarian = 1 xor 0) and (coeliac = '$coeliac' or coeliac = 1 xor 0)";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
PHP's NULL have no significance when converted to a string (the SQL query), they will evaluate to empty and your query will look like nutFree = '' and vegetarian = '' and coeliac = ''.
If those fields are 0 in the database, you must set the variables to 0 then.
On a second case, if they are NULL in the database, you must change both your query and the way you define NULL here.
First, those string wrappers should go away. You don't need them for numbers anyway, those are supposed to wrap strings only:
$sql = "SELECT * FROM products WHERE vegan = $vegan and nutFree = $nutFree and vegetarian = $vegetarian and coeliac = $coeliac";
And then instead of setting the variables to NULL, you will set them to the string "NULL".
$nutFree = "NULL";
This will make NULL show on the SQL query as its expected to.

Categories