I have a SQL table structured that way:
Id_value | id_group_value | name_group_value | name_value
I build a php/sql query to create a dropdown form getting its values which work like that:
<label>item</label>
<?php
$result = $conn->query("select id_ value,id_ group _ value, name _ group_ value, name_value FROM table WHERE id_ group _ value = 0");
echo "<select name='name_value' ><option value='' disabled selected>choose value</option>";
while ($row = $result->fetch_assoc()) {
unset($idv, $namev);
$idv = $row['id_value'];
$namev = $row['name_value'];
$id_gv = $row['id_group_value'];
$id_v = $row[' name_group_value '];
echo '<option value="'.$ idv.'">'.$namev.'</option>';
}
echo "</select>";
I can easily save values from that select form item using a '$_POST[form_item]' which I do this way and means get the $idv variable:
$sql = "INSERT INTO table (form_select_value)
VALUES ('$_POST[name_value]')";
What should I do to save another extracted value which I retrieved from the original SQL query, let’s say $namev variable, together?
Using hidden fields you can set all the values like:
<input type="hidden" name="nvalue" value="<?php echo $namev; ?>>"
And insert value like this,
$sql = "INSERT INTO table (form_select_value1,form_select_value2) VALUES ($_POST['name_value'],$_POST['nvalue'])";
Related
I have a drop down menu that is populated by pulling the IDs and company_names from a mysqli table with fields that look something like this
id - company_name - first_name - last_name - phone - email ...
row1 1 ---- ---- ---- --- ---
row2 2 ---- ---- ---- --- ---
I then use the following code to pull the id and company_name to populate the dropdown menu
$mysqli = new mysqli('localhost', 'root', '', 'clients');
$sql = "SELECT id,company_name FROM clients";
$get = $mysqli->query($sql)
?>
<h1>Invoices</h1>
<form method="post" action="processinvoices.php">
<select name="id">
<option value="0">Please Select</option>
<?php
while($row = mysqli_fetch_assoc($get))
{
?>
<option value = "<?php
$id = $row['id'];
$company_name = $row['company_name'];
echo($id . $company_name)?>" >
<?php echo($id ." ". $company_name) ?>
</option>
<?php
}
Which produces something that looks like this
Please Select
id1 companyname1
id2 companyname2
id3 companyname3
When I make a selection, say ID1 Company, I want the following code to select the appropriate row and echo the appropriate first_name associated with the ID selected. I think my problem is that when I try to $_POST['id '] to the variable $ids the id number isn't being collected making the code from echo $ids not work.
$ids = $_POST['id'];
echo $ids;
if( $mysqli->query( "SELECT * FROM clients WHERE ID = $ids" ) ) {
if( $result = $mysqli->use_result() ) {
while( $row = $result->fetch_assoc() ) {
echo $row['company_address'];
}
$result->close();
}
}
The closest answer I've seen to this issue is using jquery/ajax here but I'm looking for a purely php solution to this issue. Thanks in advance for any help provided and apologies if I haven't expressed my requirements perfectly.
You are concatenating the ID and the company name as the value for your drop down (which is the one you send). This will make your actual query to look like this:
SELECT ..... WHERE ID = id1companyname1
...which is wrong for multiple reasons.
You should only add the ID as the value:
<option value="<?= $row['id'] ?>">
<?= $row['id'] . ' ' . $row['company_name']?>
</option>
You should also secure your PHP and SQL query a bit:
// Make sure the index exist with isset(), and cast it
// as an integer (for security, since ID's are only integers)
$ids = isset($_POST['id']) ? (int) $_POST['id'] : 0;
echo $ids;
// Also, change ID in the query to id (small letters).
if ($result = $mysqli->query( "SELECT * FROM clients WHERE id = $ids" )) {
while ($row = $result->fetch_assoc()) {
echo $row['company_name'];
}
}
Note: In this case, casting the value as integer works and is enough to protect you from SQL Injections, but in general, you should use Prepared Statements instead of concatenating your queries. Specially when dealing with user inputs, which can never be trusted.
enter image description herei want to insert multiple text box value in to a single column in a table at a time
it should b like there should be name and infront of name there are text boxes to enter age of the students
so when we submit then the age entered infront of the student name it will get stored in the table with student names and ages.
(multiple students data feeding at a time)
Hi Try this change table name and column name according to yours.
Also i have query all data of table this will update all fields age if already age exist and you fill again in form. So either apply where condition in your query so that it filter only name which does not have price or add value field in form which display age if exist in database.(This is according to code you provided in comment)
<?php
$conn = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password,$mysql_database) or die("Could not connect database");
$result = mysqli_query($conn,"select * from user");
if(isset($_POST['submit'])){
$sql = "UPDATE user SET age = (CASE name ";
foreach($_POST['age'] as $key=>$value){
$sql = "UPDATE user SET age = '$value' where name = '$key'";
mysqli_query($conn,$sql);
}
$success = "updated successfully";
}
if(isset($success) && !empty($success)){
echo '<h3>'.$success.'</h3>';
}
echo '<form method="post">';
echo '<table>';
while($row = mysqli_fetch_assoc($result)){?>
<tr>
<td><input type="text" value="<?php echo $row['name']; ?>" name="name" readonly="true"></td>
<td><input type="number" name="age[<?php echo $row['name']; ?>]" placeholder='enter age'></td>
</tr>
<?php } ?>
<tr><td colspan="2">
<input type="submit" name="submit" value="Save"></td></tr>
</table>
</form>
I didn't get your example but if you want to store multiple values in a single database column, you can pass these values into an array and encode it with json_encode. After reading the values from the database you can transform it back to an array with json_decode.
Use json_encode to encode the content and then store it in database field and when you retrieve the value then use json_decode
$form_data_json = json_encode( $_POST );
I recently have been trying to make a way to easily add more fields onto my form without having to go back and add more rows to my database structure. So, to begin working on this, I created a table where the structure is this:
OptionTitle
Option1
Option2
Option3
Option4
Option5
Option6
As you can see, it goes up to 6 options, and OptionTitle is the label name of the form. Then I made another table, one that reflects the users input of the previous table. This table is named usersoption
fid
OptionTitle
Option1
Ok, so FID reflects which form it is referencing to. This way, when displaying the submitted form, it'll pull information from this table where the FID is the same. OptionTitle is the label of the form, and Option1 is the option the user submitted.
Now, onto the form where it actually includes the options to select from. Here is a simplified version of how my code is included:
$query100 = $db->query("SELECT * FROM options WHERE fid='" . $id . "'");
while($row2 = mysqli_fetch_array($query100))
{
echo "
<div class=\"divform\" id=\"optiontitle\">
<label for=\"optiontitle\">$row2[optiontitle]:</label>
<select name=\"option1[]\" id=\"option1\">";
echo "<option value='$row6[option1]'>$row6[option1]</option>";
echo "<option value='$row6[option2]'>$row6[option2]</option>";
echo "<option value='$row6[option3]'>$row6[option3]</option>";
echo "<option value='$row6[option4]'>$row6[option4]</option>";
echo "<option value='$row6[option5]'>$row6[option5]</option>";
echo "<option value='$row6[option6]'>$row6[option6]</option>";
echo "
</select>
</div>
";
}
As you can see, the select name is option1[]. This is so I can have multiple select fields on the same form, and in return this will bring over the multiple difference select fields onto the submitted process. So now onto where my issue is, in the submission process. Here is what I have so far:
foreach($_POST['option1'] as $val){
$val = $db->escape_string($val);
$query30 = $db->query("INSERT `usersoption` SET `gid` = '".$id."', `fid` = '".$fid."', `optiontitle` = 'Where OptionTitle should go', `option1` = '$val'")or die( mysqli_error());
}
As you can see, I can successfully bring the option through a foreach statement. What I can't do, is bring in the OptionTitle. It seems almost unnecessary to bring in the OptionTitle, but it is necessary for the person reading the submitted form to know which option was being submitted. I'm not sure how to carry the OptionTitle over, it seems simple but all my attempts failed miserably. I did some research and one of the suggestions was to create a hidden input with the name and carry it over that way. Here is the addon that would be in the form:
<input type=\"hidden\" name=\"optiontitle[]\" value=\"test\">
This would be added on to the form and then carried over, but the issue is how do I bring it over? I would need to do a multiple foreach statement which does not work. For example, here was what I tried to bring over (it did not work):
foreach($_POST['option1'] as $val) && ($_POST['optiontitle'] as $val2)){
$val = $db->escape_string($val);
$val2 = $db->escape_string($val2);
$query30 = $db->query("INSERT `usersoption` SET `gid` = '".$id."', `fid` = '".$fid."', `optiontitle` = '$val2', `option1` = '$val'")or die( mysqli_error());
}
Have you tried giving your option array a key?
echo "<select name=\"option1[$row2[optiontitle]]\" id=\"option1\">";
Then change your foreach to:
foreach($_POST['option1'] as $title=>$val)
You can use key in foreach to access more array:
Try this code:
foreach($_POST['option1'] as $key=>$val){
$val = $db->escape_string($val);
$val2 = $db->escape_string(isset($_POST['optiontitle'][$key])?$_POST['optiontitle'][$key]:'');
$query30 = $db->query("INSERT `usersoption` SET `gid` = '".$id."', `fid` = '".$fid."', `optiontitle` = '$val2', `option1` = '$val'")or die( mysqli_error());
}
For the hidden input solution: Just do each query as you normally would, but add $_POST['optiontitle']:
foreach($_POST['option1'] as $val){
$val = $db->escape_string($val);
$query30 = $db->query("
INSERT `usersoption` SET
`gid` = '".$id."',
`fid` = '".$fid."',
`optiontitle` = '".$_POST['optiontitle']."',
`option1` = '$val'
")or die(mysqli_error());
}
By the way you should read up on prepared statements. These allow you to sanitise your data before inserting into the database. They are essential to good coding practise.
I have a PHP form that is collecting information and writing it to a database and it is working correctly. I have one field that is a select to choose entries from an existing table. I would like that result to be inserted into a different table but can't get the insert into to work. I would like to insert the FacilityName field chosen in the select to table2.
$result = mysql_query("SELECT * FROM facility");
print "<select name=\"Id\" > \n";
while ($row = mysql_fetch_array($result)){
$Id = $row['Id'];
$FacilityName = $row['FacilityName'];
print "<option value=$Id>$FacilityName\n";
i am new here but i have a problem in inserting the id and the value of the checkboxes into my database here is the code of the form:
<?php
include('db.php');
$sql = "select * from sheet1 order by course_level asc";
$r = mysqli_query($dbc,$sql) or die(mysqli_error($dbc));
$co = '';
while($row = mysqli_fetch_array($r)) {
$co .= '<tr><td>'.$row['course_level'].'</td><td><input name="courses[]"
type= "checkbox" value = "'.$row['course_code'].'">'.$row['course_code'].'
</td> <td>'.$row['course_title'].'</td><td>'.$row['course_lecturer'].'
</td><input type=hidden name=cid[] value="'.$row['cid'].'">
</tr>';
}
?>
And this is the action code:
<?php
include('db.php');
if(isset($_POST['courses']))
echo 'lie';
else
echo 'true';
foreach($_POST['courses'] as $row=>$id){
$courses=$id;
$cid = $_POST['cid'][$row];
$sql = "insert into selected_courses values ('','$courses','$cid')";
$r = mysqli_query($dbc,$sql);
}
if($r)
echo 'done';
?>
thanks a lot.
You have several problems here, the main one being you are attempting to store two different reference values to the same row (course_code and cid) in your selected_courses table. You should really only store the primary key (cid?).
I'd suggest dropping the course_code column from your selected_courses table, remove the hidden input and structure your checkbox like this
<input type="checkbox"
name="courses[]"
value="<?php echo htmlspecialchars($row['cid']) ?>">
Then your INSERT query simply becomes
// Forget mysqli, move to PDO
$stmt = $dbc->prepare('INSERT INTO selected_courses (cid) VALUES (?)');
$stmt->bindParam(1, $cid);
foreach ($_POST['courses'] as $cid) {
$stmt->execute();
}