Getting value from php form - php

I am trying to insert into a database posted form values, retrieved from an html form that was generated via php. However it is not inserting the values, however I do see the values when I print the posted variables. Here is the code.
This is the form written in php that outputs html
<?php
$find = mysql_query("SELECT file_name FROM chemlab_files WHERE student_id = '$student_id'") or die ("Could not search!");
while($row = mysql_fetch_array($find)){
$file_name = $row['file_name'];
$_SESSION['file_name'] = $file_name;
echo "<label class='checkbox'><input type='checkbox' name='file_name[]' value='{$file_name}'>$file_name</label><br><input type='text' name='description[]' value='' placeholder='description'>";
}
?>
This is the form handler
//description
if(isset($_POST['description'])){
foreach($_POST['description'] as $description){
$file_name_description = mysql_real_escape_string($description);
//print_r($file_name_description);
}
}
$result = mysql_query("SELECT * FROM chemlab_files WHERE student_id='$student_id'") or die (mysql_error());
//if the student_id does exist, proceed
if($result==1){
//insert into chemlab_files update description
$insert_file_name_description = mysql_query("UPDATE chemlab_files SET description='$file_name_description' WHERE file_name='$file_name'");
}else{
echo 'something went wrong during sharing!';
exit();
I can print the variable $file_name_description but cannot insert into the database.
To be more clear the form has multiple fields, for ever file_name (checkbox with value ="$file_name") has a description field. When I do print_r for $file_name and $description I get the values for all the fields. However when I go to insert the description into the database nothing happens.

INSERT INTO table_name
VALUES (value1, value2, value3,...)
you need this.

If you are trying to create a new database record, shouldn't your sql be an INSERT statement like
INSTERT INTO chemlab_files SET (description, name) VALUES ('$file_name_description','$file_name')

I see two problems:
I do not understand why the text input in your HTML is an array (description[])
I don't see why you iterate it at the beginning, and you always set the $file_name_description to the last value. Are you trying to append all posted description inputs to the $file_name_description variable? If yes, then you should write .= instead of =

Related

Trying to get value from a select field, which I filled with an SQL query

I come to you in dire need.
What I'm trying to do is to make a form with a dropdown menu, that menu is filled by fetching id's from a table.
<form method="post" action="addWorkExperience.php">
<select name="employerSelection">
<?php
$sql = mysqli_query($conn, "SELECT employer_id FROM employers");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"eID\"> " .$row['employer_id'] . "</option>";
}
?>
</select>
And to my understanding my selected option should be accessible through the $_POST variable like so:
$eValue = $_POST['employerselection'];
or:
$sValue = $_POST['eID'];
These variables would be used in my insert query to write my choice back to the SQL database. However, for some reason it just doesn't. Every other inputfield I trow at it works, except the select field.
Am I missing something?
You have a typo, instead of
$eValue = $_POST['employerselection'];
try
$eValue = $_POST['employerSelection'];
In further situations, you can help yourself by simply using
var_dump($_POST);
that will output all variables that $_POST contains

Pass value from one PHP file to another

I'm trying to pass a value which is input into a box on one Php page (itinerary.php) into another Php page ('submit.php') so it can, from there, be saved into a database. But I can't quite figure out how to get it across. I've tried using GET as you can see from code below, but I am already using a GET statement to receive and acknowledge another value from that very same page 'submit'. I guess I am overcomplicating it, but my knowledge of Php is still pretty limited at this stage so any ideas would be appreciated!
This is an extract from the itinerary.php file (it sits within a Bootstrap/Html framework. Note the entry which contains the input box for the sequence number).
<h3><br>YOUR ITINERARY</h3>
<?php
//Display contents of itinerary
if(!empty($_SESSION['itinerary'])){
//Retrieve details of each location in array from database
$query = "SELECT * FROM locations WHERE loc_id IN (";
foreach ($_SESSION['itinerary'] as $loc_id=>$value)
{$query.=$loc_id.',';}
$query = substr($query, 0, -1).')ORDER BY loc_id ASC';
$result = mysqli_query($db, $query);
echo'<table><tr><th colspan="5">LOCATIONS IN YOUR ITINERARY</th></tr>';
//Display locations in array
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$loc_id = $row['loc_id'];
echo"<br><td>{$row['loc_name']}</td></tr><br>
<td>{$row['loc_desc']}</td>
<td><p>Seq. No</p><input type=\"text\" size=\"3\" name=\"sequence\" value=????????>NOT SURE WHAT TO ADD INTO THIS LINE TO RETAIN THE INFO THAT IS INPUT</td>
<td><a href=remove_loc.php?value=$loc_id>Remove location</a><br></br></td>
</tr><br></table>";
}//while
print_r($_SESSION);
mysqli_close($db);
}//if
else {echo '<p><br>Your itinerary is empty.<br></p>';}
echo '<br><p>
<a href=submit.php?submit>Save itinerary</a>
<a href=clear_itin.php?clear>Clear itinerary</a>
Your details
Logout
</p>';
?>
And this is where I am trying to receive it and then use it in a SQL command to add to the database. (Again, this is within a Bootstrap framework)You can ignore the first SQL Insert statement as it is passing other info in successfully anyway..
<div class="row">
<div class="col-md-9">
<?php
if (isset($_GET['sequence'])){
$sequence = $_GET['sequence'];
}//if
if (isset($_GET['submit'])){
$query = "INSERT INTO itineraries (user_id, date_created) VALUES (".$_SESSION['user_id'].", NOW())";
$result = mysqli_query($db, $query);
$itinerary_id = mysqli_insert_id($db);
$retrieve_locs = "SELECT * FROM locations WHERE loc_id IN (";
foreach ($_SESSION['itinerary'] as $id=>$value)
{$retrieve_locs.=$id.',';}
$retrieve_locs = substr($retrieve_locs, 0, -1).')ORDER BY loc_id ASC';
$result = mysqli_query($db, $retrieve_locs);
//Store items in itin_locs db
while ($row = mysqli_fetch_array ($result, MYSQLI_ASSOC)){
//This is the command I have been trying to use, commented out. The second one below this works fine, but obv doesn't input a sequence number.
//$insert_locs = "INSERT INTO itin_loc (itinerary_id, loc_id, sequenceNo) VALUES ($itinerary_id, ".$row['loc_id'].", $sequence)";
$insert_locs = "INSERT INTO itin_loc (itinerary_id, loc_id) VALUES ($itinerary_id, ".$row['loc_id'].")";
$insert_result = mysqli_query($db, $insert_locs);
echo mysqli_error($db);
if ($insert_result === FALSE) {
die("Query failed!" . mysql_error() . $insert_locs);}
}//while
mysqli_close($db);
echo"<p>Your itinerary is saved!. Itinerary number is #".$itinerary_id."</p><br>";
$_SESSION['itinerary']= NULL;
echo '<p>
Your details
Logout
</p>';
}//if
else {echo '<p>Your itinerary is empty.<br></br></p>';}
?>
Use a form on your HTML page to hold all the input fields in the table.
Also instead of anchor "a" tag use a submit button to submit the form to other page.
Use some thing like:
Send value of submit button when form gets posted

Trying to use query variable and form data to change tables in database

So as said in title I'm trying to use the query variable given from the page which directs to this one and the form data from THIS page to manipulate the database. I can't seem to get it right and I have no idea what I'm doing wrong. The code snippet looks like this:
<?php
$ware_number = $_GET['id'];
Echo "<form action='usernamecheck.php' method='post'>";
Echo 'Username:<br>';
Echo '<input type="text" name="usernamecheck" size="14"><br>';
Echo 'Password:<br>';
Echo '<input type="password" name="passwordcheck" size="14"><br>';
Echo '<input type="submit" value="Send">';
Echo '</form>';
if (isset($_POST['usernamecheck'])) {
$sql2 = "SELECT * FROM `storedata`.`users` WHERE `username` LIKE '$_POST[usernamecheck]'";
$found_user_id = mysql_query($sql2, $conn);
print $found_user_id;
}
if (isset($_POST['usernamecheck'])) {
$sql3 = "INSERT INTO `storedata`.`basket` (user_id, ware_id, number, complete)
VALUES
('$found_user_id', '$ware_number', 1, 0)";
$derp = mysql_query($sql3, $conn);
print $derp;
}
?>
The document itself is usernamecheck.php, and I was just printing to try and locate the error. When i check the basket table nothing has happened, even though no error is displayed. Right now the variable $ware_number is causing errors. What am I doing wrong?
I have also made user_id and ware_id foreign keys in the storedata.basket table, since they are primary keys in their own respective table. This means they can only be specific values, but I'm testing with these values, primarily 1's and 0's...
What if $_GET['id'] is not set? it will fail. Also please read up into correct usage of SQL in PHP. Your code is vulnerable to SQL injection attacks and whatnot.
EDIT:
updated piece of code
if(isset$_GET['id'] && is_numeric($_GET['id']))
{
$ware_number = $_GET['id'];
Echo "<form action='usernamecheck.php?id=" . $_GET['id'] . "' method='post'>";
.....

Html form generated with PHP not inserting all Arrays

I have a form that was generated with php
Below is in my account.php
$student_id is set by a session and I am finding all the file_names that are associated with that student_id. The I generated an HTML form using php where each of the file_names for that student are displayed in a checkbox format with a description input below each checkbox.
<?php
$find = mysql_query("SELECT file_name FROM chemlab_files WHERE student_id =
'$student_id'") or die ("Could not search!");
while($row = mysql_fetch_array($find)){
$file_name = $row['file_name'];
$_SESSION['file_name'] = $file_name;
echo "<label class='checkbox'><input type='checkbox' name='file_name[]'
value='{$file_name}'>$file_name</label><br><input type='text' name='description[]'
value='' placeholder='description'>";
}
?>
This is now part of the handler.php I am having trouble with it does insert but it insert blanks for the checkboxes not checked off
if(is_array($_POST['description'])){
foreach(str_replace('#', '', $_POST['description']) as $strip){
$description_backslash = $strip . '/';
$description = mysql_real_escape_string($strip);
$query = "INSERT INTO file_list(description) VALUE ('$description')";
$q= mysql_query($query) or die ('Error posting data');
//print_r($description);
//print '<br>';
}
Checkboxes that are not checked, do not get sent to the server so if not all checkboxes are checked, there will be a mis-match between the checkbox indices and the file_name inputs.
To avoid that problem, you would have to add indices to your form fields so that you know what description belongs to what file_name and to be able to loop over the description's and discard the ones that are not set.

Edit script for dynamic form data

I'm working on a grading system, and I have many tables with the prefix rubrics_. Each table has skills for different categories of grading.
I have a form being looped, which displays all skills that have been created for this particular assessment document. The input fields are populated with whatever information they entered when creating the "rubric. (hence the value $row2['skill']). I named the field evidence_[unique id] to try and identify each skill value.
$sql2 = "select * from rubrics_evidence where rubricid = '$id'";
$result2 = mysql_query($sql2) or die (mysql_error());
while($row2=mysql_fetch_array($result2)) {
echo "<tr><td><input type='text' value='".$row2['skill']."' name='evidence_".$row2['id']."' size='100' /></td></tr>";
}
My objective is to make it so these skills are edited when a new value is entered (appending the existing value). However, by naming each skill with something like evidence_[id], I'm not sure how to take that data and process it.
What I mean by that is, I can't figure out how to reprocess these input fields once they are submitted. I can't tell the script to look for evidence_id because each id is unique.
Anyone know how to accomplish this? I'd greatly appreciate it.
Thanks!
You can obtain the field names in your processing code the same way you created them
//make sure you include the $id from that form somewhere in the form again
$sql = "SELECT id FROM rubrics_evidence WHERE rubricid = " . $_POST['id'];
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$value = $_POST['evidence_' . $row['id']];
//do something with the new value
}

Categories