Inserting to DB via foreach - php

So I have these code below. The first one is a loop which echos all the requirements came from the database and write it in a checkbox form. So what I did is named it in an array form which is requirementItems[].
The next code is all about checking and inserting. If the checkbox is checked, the $state variable will have the value of 1 else, 0.
My problem is that, when I tried to leave a checkbox unchecked, it doesn't record into the database. But if it is checked, it successfully insert the data.
FIRST
<?php
$query = $db->prepare("SELECT * FROM tbl_requirements WHERE reqStatus = 1");
$query->execute();
while($result = $query->fetch(PDO::FETCH_ASSOC)){
$requirementID = $result['reqID'];
$requirementName = $result['reqName'];
echo "
<div class='row'>
<div class='col-md-5'>
<div class='checkbox'>
<label>
<input type='checkbox'value='$requirementID' title='$requirementID' name='requirementItems[]'>
$requirementName
</label>
</div>
</div>
</div>
";
}
?>
SECOND
<?php
if(isset($_POST['passSubmit'])){
$rsrvReqID = trim($_POST['reqID']);
$customerID = $_GET['cusID'];
$reservedProperty = $_GET['propertyID'];
$paymentID = $_GET['paymentID'];
$requirementItems = $_POST['requirementItems'];
foreach($requirementItems as $reqItem) {
$state = (isset($reqItem)) ? 1 : 0;
$query = $db->prepare("INSERT INTO tbl_rsrvrequirements (rsrvReqID, customerID, propertyID, paymentID, reqID, rsrvReqState)
VALUES (:rsrvReqID, :customerID, :reservedProperty, :paymentID, :reqID, :state)");
$query->execute(array(
":rsrvReqID" => $rsrvReqID,
":customerID" => $customerID,
":reservedProperty" => $reservedProperty,
":paymentID" => $paymentID,
":reqID" => $reqItem,
":state" => $state
));
$reqNEW = str_replace('REQ','',$rsrvReqID);
$requireID = str_pad(trim($reqNEW) +2,7,0,STR_PAD_LEFT);
$rsrvReqID = 'REQ'.$requireID;
}//foreach()
echo"<meta http-equiv='refresh' content='0; url=summary.php?reqID=$rsrvReqID' >";
}//if(isset())
?>

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

PHP query when a user submit a form select

I want to delete a row from a form select when i click on submit input with an sql query,(i think i am wrong on something, but i don't understand what) as you can see below for my example :
My list and the blue case i want to delete on submit
My actual code, and the $supp i want to do when the user click on submit
`
<form method="POST">
<select>
<?php
// Drop Down
$res = null;
$sql2 = "SELECT `sinistre_type` FROM `form_sinistre`";
$query2 = $db->prepare($sql2);
$query2->execute();
// INIT > PREP > EXEC > SUPP
$supp = "DELETE FROM `form_sinistre` WHERE `sinistre_type` = '$res'";
$query3 = $db->prepare($supp);
$sendbddsupp = $query3->execute();
echo "<option disabled selected>..Choix Possible..</option>\n";
while ($res = $query2->fetch(PDO::FETCH_NUM)) {
echo "<option name='res'>" . $res[0] . "</option>\n";
}
?>
</select>
<input type="submit" value="Supprimer">
</form>
`
Some $_POST config
`
<?php
session_start(); //debut de SESSION
include("config.php"); //Appel de la bdd
// ... INIT VARIABLES ...
$sinistre_type = "";
$sinistre_desc_dmg = "";
$list = "";
if (empty($_POST)) { // SANS COOKIES / POST
} else { // AVEC COOKIES / POST
$sinistre_type = $_POST['nom'];
$sinistre_desc_dmg = $_POST['vent'];
$res = $_POST['res'];
$sql = "INSERT INTO `form_sinistre` (sinistre_type, sinistre_desc_dmg) VALUES (:sinistre_type, :sinistre_desc_dmg)";
$query = $db->prepare($sql);
$query->execute(array(':sinistre_type' => $sinistre_type, ':sinistre_desc_dmg' => $sinistre_desc_dmg));
}
var_dump(isset($_POST['res']));
?>
`
(EDIT : my list is linked with my db and working that why i want to send sql query)
Thanks by advance for your help, if you need more information let me know :)

User value used instead of PHP value in textbox

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!

Textarea not reading any input

The textarea is not reading any input that is typed into the box. Initially, I was using PHP to check if the textarea was empty, and was recieveing an error there. So I removed that check, to see if it was php that was causing the issue, and added the required="required" attribute to the textarea tag, and even that is coming back with Please fill out this field. I am not quite sure where I am going wrong with my code, I had it working previously, then all of a sudden it stopped working, and I am completely confused as to why. I also looked at various other posts about the textarea not submitting, and ensured that I was checking the post with the name, not the ID; and making sure the textarea was submitting to the same form as the submit button. I have also tried it without specifying the form on the textarea tag.
HTML Code:
<form action="" method="post" id="CreateTopicForm">
<input type="hidden" name="create-topic" />
<span class="secondary radius label"><strong>Title</strong></span>
<input type="text" name="title" id="title" />
<span class="secondary radius label"><strong>Message</strong></span>
<textarea name="content" id="content" required="required" form="CreateTopicForm"></textarea>
<?php if($_SESSION['user']['account_type'] >= 3): ?>
<span class="secondary radius label"><strong>Sticky Topic</strong></span>
<input type="checkbox" name="sticky" /><br />
<?php endif ?>
<input type="submit" value="Post Topic" class="topic-post" />
</form>
PHP Code:
/* Retrieve necessary variables */
$fid = $_GET['fid'];
/* Get Forum Information */
$query = "SELECT * FROM bkg_forums where forum_id = :id";
$query_params = array(
':id' => $fid
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
} catch(PDOException $e) {
$error[] = $pdoerror;
}
$forum = $stmt->fetchAll();
/* Begin the database upload */
if(!empty($_POST)){ /* Plan to change to if($_REQUEST['submit']) */
/* Check if data was actually submitted */
$db->beginTransaction();
/* DO SOME ERROR CHECKING. MAKE SURE FIELDS ARE NOT EMPTY. */
if(empty($_POST['title'])){
$error[] = "Sorry! You must enter a title!";
}
/* Previously had a check if $_POST['content'] */
/* GENERATE SOME VARIABLES NEEDED TO INSERT INTO TABLES. ACCOUNT_TYPE IS TEMPORARY*/
if($_SESSION['user']['account_type'] == 0) {
$account_type = "Normal";
$color = "white";
} elseif($_SESSION['user']['account_type'] == 1) {
$account_type = "Donator";
$color = "#F4FA58";
} elseif($_SESSION['user']['account_type'] == 2) {
$account_type = "Moderator";
$color = "#2EFE2E";
} elseif($_SESSION['user']['account_type'] == 3) {
$account_type = "Community Manager";
$color = "#0000FF";
} elseif($_SESSION['user']['account_type'] == 4) {
$account_type = "Administrator";
$color = "#DF0101";
}
if(isset($_POST['sticky'])){
$sticky = 1;
} else {
$sticky = 0;
}
if(!isset($error)){
/* INSERT INTO TOPICS TABLE */
$query = "INSERT INTO bkg_topics (
forum_id,
icon_id,
topic_approved,
topic_title,
topic_text,
topic_poster_id,
topic_poster,
topic_poster_color,
topic_post_time,
topic_status,
topic_type
) VALUES (
:forumid,
:iconid,
:topicapproved,
:topictitle,
:topictext,
:topicposter_id,
:topicposter,
:topicposter_color,
:topicpost_time,
:topicstatus,
:topictype
)";
$query_params = array(
':forumid' => $fid,
':iconid' => 1,
':topicapproved' => 1,
':topictitle' => $_POST['title'],
':topictext' => $_POST['content'],
':topicposter_id' => $_SESSION['user']['id'],
':topicposter' => $_SESSION['user']['displayname'],
':topicposter_color' => $color,
':topicpost_time' => time(),
':topicstatus' => 0,
':topictype' => $sticky
);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$lastid = $db->lastInsertId();
/* Retrieve the last id of a topic, used to generate some links. */
/* UPDATE FORUM TABLE */
$query = "UPDATE bkg_forums SET
`forum_last_post_id` = :lastpostid,
`forum_last_post_topic_id` = :lastposttopicid,
`forum_last_post_title` = :lastposttitle,
`forum_last_poster_id` = :lastposterid,
`forum_last_post_time` = :lastposttime,
`forum_last_poster_name` = :lastpostername,
`forum_last_poster_color` = :lastpostercolor
WHERE `forum_id` = :forumid
";
$query_params = array(
':lastpostid' => null,
':lastposttopicid' => $lastid,
':lastposttitle' => $_POST['title'],
':lastposterid' => $_SESSION['user']['id'],
':lastposttime' => time(),
':lastpostername' => $_SESSION['user']['displayname'],
':lastpostercolor' => $color,
':forumid' => $fid
);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
if($fid == 13){
$query = "INSERT INTO updates (
title,
content,
`date`,
`user`,
`topic_id`
) VALUES (
:title,
:content,
:date_posted,
:user_posted,
:topic_id
)";
$query_params = array(
':title' => $_POST['title'],
':content' => $_POST['content'],
':date_posted' => time(),
':user_posted' => $_SESSION['user']['displayname'],
':topic_id' => $lastid
);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
try {
$db->commit();
$post_ok = 1;
} catch(PDOException $e) {
$erroradmin[] = $e->getMessage();
$db->rollback();
}
if(isset($post_ok)): ?>
<script>
location.href = "http://www.boundlessknights.com?viewtopic&fid=<?php echo $fid; ?>&tid=<?php echo $lastid; ?>";
</script>
<?php else: ?>
<?php $error[] = "Your topic did not post."; ?>
<?php endif; ?>
<?php
}
}
?>
Questions I looked at:
Form Post Not Reading Any Value
Cannot Get the Value of a Textarea via Post Method
Textarea Not Posting with Form
Textarea Returns Empty Value in PHP Post
TinyMCE does not keep the underlying textarea in sync at all times. Normally, when you post the form, TinyMCE will update the textarea before the form is posted but the process seems to be stopped by the required attribute. You can use the following API call to force TinyMCE to update the textarea:
tinymce.triggerSave();
This will force TinyMCE to update the textarea when its called. You can either:
Do this in the onsubmit event of the form
Do this in the TinyMCE init:
tinymce.init({
selector: "textarea",
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
}
});
Your page is using TinyMCE editor. It is giving the following error in the console: An invalid form control with name='content' is not focusable.
Fixing that will fix your problem.
Hmmm, did you try to remove this "form" attribute from your Textarea ?
<textarea name="content" id="content" required></textarea>
Tell us what it do when u try.
Change this
<textarea name="content" id="content" required="required" form="CreateTopicForm"></textarea>
to this
<textarea name="content" id="content" required="required" ></textarea>
You might not be able to post anything because you've NOT specified the action attribute of your form.
<form action="" method="post" id="CreateTopicForm">
Set it to the name of the php file (with the proper path to the file),
and it should work.
Note: To make sure the the $_POST array contains your form submitted values, do a var_dump($_POST).

Form processing

what I'm trying to do is run a select statement for each answer to select the answer in the database where the questionID = $i and the userID = $userID so I have the query like this set up so far but not sure what I'm missing or am I right and not missing anything? Also no matter what i do both fields have values but I'm still getting the error message that I need to fill out both form fields.
<?php
$i = 1;
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
?>
<dl>
<dt style="width: 190px;"><label for="answer[<?php echo $row['id']; ?>]"><?php echo $row['question'] ?></label></dt>
<dd><input type="text" name="answer<?php echo $i ?>[<?php echo $row['id']; ?>]" size="54" /></dd>
</dl>
<?php
++$i;
}
?>
if (empty($_POST['answer1'][$i]) || trim($_POST['answer1'][$i])=="") {$errors = "yes";}
if (empty($_POST['answer2'][$i]) || trim($_POST['answer2'][$i])=="") {$errors = "yes";}
// Error checking, make sure all form fields have input
if ($errors == "yes") {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => true, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1 = mysqli_real_escape_string($dbc,$_POST['answer1'][$i]);
$answer2 = mysqli_real_escape_string($dbc,$_POST['answer2'][$i]);
$query = "SELECT * FROM manager_users_secretAnswers WHERE questionID = '".$questionID."' AND userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
echo $query;
You can have a problem with php type autoquessing. Let suppose thatyou have questions with ids: 3,5,7,8 then you are using:
empty($_POST['answer1'][$i])
$_POST['answer1'][3] so you are fetching third element of array.
So I suggest to use not array notation, but:
For input name: answer|${id} or answer_${id} instead of answer[$id]

Categories