I am trying to build a PHP PDO query, based from a set of checkboxes that a user has selected on the previous page.
So i have the following checkboxes in my form:
<input type="checkbox" name="websites[]" value="one" id="one">
<input type="checkbox" name="websites[]" value="two" id="two">
<input type="checkbox" name="websites[]" value="three" id="three">
Once submitted i then want to build a pdo query and query parameters based from what checkboxes the user selected - they have to all be in the one query though. I know that any checked boxes will be stored in my $_POST['website'] array but how can i then take that and put them in the query? For example say the user selected one and three only, i then want to only select those fields from my database table:
$results = $_POST['websites'];
$query = "
SELECT
one,
three
FROM
table
";
How can i do the above?
First of all you should use a white-list of allowed fields to avoid sql injection. Then you need to check every sent-in entry to see if it exists in your white-list and add it to the query if it does.
So something like:
$allowed_fields = array(...);
$fields = array();
// only checked fields are sent to the server
foreach ($_POST['websites'] as $value)
{
if (in_array($value, $allowed_fields))
{
$fields[] = $value;
}
}
$query = 'SELECT `' . implode('`, `', $fields) . '` FROM table';
Related
I have a user input with checkboxes. The number of checkboxes can vary in quantity because they are generated with a fetch. I would like to transfer the respective value per selected checkbox into a table and create a row for each selected checkbox. My problem is that with my current code only the value from the last checkbox is taken. Not sure how to implement a foreach here.
My code currently looks like this:
HTML Checkbox example which can repeat from 1 to unlimited. Name is always the same but value and id is changing:
<input type="checkbox" class="custom-control-input" name="questionaire_id" id="100" value="100">
<label class="custom-control-label mb-3" for="100"> Some_Name - 100 </label>
PDO Query PHP
if (isset($_POST['speichern'])) {
$questionaire_id = $_POST['questionaire_id'];
$statement = $pdo->prepare("INSERT INTO audit_bundles(questionaire_id) VALUES (:questionaire_id)");
$result = $statement->execute(array('questionaire_id' => $questionaire_id));
}
I have found a solution which works for me. It is taking the value from a selected checkbox and is creating a row. Does not matter how many check boxes i have.
if (isset($_POST['speichern'])) {
$statement = $pdo->prepare("INSERT INTO audit_bundles (questionaire_id) VALUES (?)");
$statement->bindParam(1, $questionaire_id);
foreach ($_POST['questionaire_id'] as &$value) {
// insert row
$questionaire_id = $value;
$statement->execute();
}
Problem statement:
I have a form with multiple checkbox Fields, i have validated it so
user can select maximum 9 checkbox and atleast 1 with jquery.
I collect the Form checked values using Post method.
i have mysql table with 12 columns.
first 3 columns are "id", "rollnum", "selectStatus"
Through session variables created during Login, i get roll number of student. So i can Run Update Query on particular row.
Question: How do i Update those 9 subject columns according to user checked inputs. Note : i stored those checked input field values in an array.
Code
<form action="index.php" id="form-3" method="post">
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="ucs303">UCS303 Operating Systems
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="ucs406">UCS406 Data Structures and Algorithms
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec401">UEC401 Analog Communication Systems
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec612">UEC612 Digital System Design
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec307">UEC307 Electromagnetic Field Theory & Trans Lines
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec502">UEC502 Digital Signal Processing
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec510">UEC510 Computer Architecture
<button type="submit" name="year-3-submit">Submit Selection</button>
</form>
<?php
if(isset($_POST['year-3-submit'])){
if(!empty($_POST['year-3-checkbox'])){
$subjectCheckList = array();
$subjectCheckList = $_POST['year-3-checkbox'];
}
}
?>
It depends on user how many checkbox is selected.
I donot know how to write UPDATE sql query which updates values of number of columns == size of array.
for example:
User 1 has selected 3 checkbox and submitted form, we have array of size 3 and UPDATE 3 columns of table.
User 1 has selected 6 checkbox and submitted form, we have array of size 6 and UPDATE 6 columns of table.
I donot want to write 9 switch case statements for all possible sizes
of array. Any idea? please?
Based on OP's comments, you can make the code generic as follows:
// Check if atleast one subject has been selected
$selectedSubjects = array_filter($subjectCheckList);
// If no subject selected
if (empty($selectedSubjects)) {
$sql = "UPDATE subjectmaster
SET substatus = 0
WHERE rollno = '" . mysqli_real_escape_string($rollnumber) . "'";
} else {
// Initialize the sql string
$sql = "UPDATE subjectmaster
SET substatus = 1 ";
$i = 1;
foreach ($subjectCheckList as $subject) {
$sql .= ", sub" . $i . " = '" . mysqli_real_escape_string($subject) . "' ";
}
$sql .= " WHERE rollno = '" . mysqli_real_escape_string($rollnumber) . "'";
}
Also, note the use of mysqli_real_escape_string. It helps in preventing SQL injection. For better ways to prevent SQL injection, you may check How can I prevent SQL injection in PHP?
Well, 1st of all it is not clear what should be the default valued for each column.
Since your MySQL columns are set by numbers (sub1, sub2, etc) then your form should represent them accordingly, with the proper value. for example:
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="1">
This way, you can loop easily and update the table (I assume the sub columns are TINYINT(1) DEFAULT NULL) :
<?php
if(isset($_POST['year-3-submit'])){
if(!empty($_POST['year-3-checkbox'])){
$subjectCheckList = array();
$query = "UPDATE table SET ";
foreach ($_POST['year-3-checkbox'] as $key => $value) {
$query .= " sub" . $value . " = 1, "
}
$query = substr($query, 0, -1);
}
}
?>
Hope this helps
Guy
You can also use array_filter, array_combine and array_slice.
<?php
$subs = [':sub1',
':sub2',
':sub3',
':sub4',
':sub5',
':sub6',
':sub7',
':sub8',
':sub9'
];
// use $dataFromForm = array_filter($_POST['year-3-checkbox'])
$dataFromForm = ['11111',
'222222',
'3333333'];
$dbh = new PDO('mysql:host=localhost;dbname=test', 'root', '*******');
$sql = 'UPDATE test SET sub1 = :sub1, sub2 = :sub2, sub3 = :sub3, sub4 = :sub4, sub5 = :sub5, sub6 = :sub6, sub7 = :sub7, sub8 = :sub8, sub9 = :sub9';
$sth = $dbh->prepare($sql);
$sth->execute(array_combine(array_slice($subs, 0, count($dataFromForm), $dataFromForm)));
I make a form, where there is ID of a shop:
<input type="text" name="shopId">
and there is a multiple choice select:
<select name="cars" multiple required>
after i get selected options, i have to pass them to a table in the database; table consists of 2 columns: shopId and car. The thing is it passes only one option and it is impossible to have a few rows added to the table like in one shop two or three models. I suppose i have to pass the data like an array or something. Can you help me, please.
$shopId = $_GET["shopId"];
$cars = $_GET["cars"];
this is a query:
$query = "INSERT INTO shops (shopId, car) VALUES ($shopId, $cars)";
I'd say given the constraints, the only option you have is to combine all the selected options into a single comma separated string (using PHP's built-in function called implode http://php.net/implode), then insert the shopID and the comma-separated-list of cars into a new row. I'd do it like this:
<?php
if ($_POST) {
$cars_string = implode(', ', $_POST['cars']);
$sql = '
INSERT INTO
`my_table` (
`shopID`,
`cars`
)
VALUES (
'. $_POST['shopID'] .',
"'. $cars_string .'"
)
';
mysql_query($sql) OR die(mysql_error());
}
?>
<form method="post" action="">
Shop ID: <input type="text" name="shopID"/> -
<select name="cars[]" multiple="multiple">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="honda">Honda</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</select>
<input type="submit" name="Submit"/>
</form>
This is the best solution given the constraints you've provided. However, I do not see the logic in only being able to add a single row per form submit. That is not a good database design, especially in the long-term.
Please notice how the <select> element has the name of name="cars[]" and pay close attention to the open/close square brackets after the word cars[]. This will allow multiple options to be passed through the form, instead of only one. This is a critical difference and it should not be overlooked, as #bart2puck mentions in his solution. Also, the most browser-friendly way to allow users to select multiple options is to use the attribute multiple="multiple" in your <select> element.
you are getting only 1 insert because you are setting the value of $_GET['cars'] to the last selected item in your multiple. to acheive what you are looking for set the select name of cars to cars[]. When you goto process this you will now have an array in $_GET data.
then loop through that to do your inserts.
$shopId = $_GET['shopId'];
foreach ($_GET['cars'] as $value)
{
$ins = "INSERT INSERT INTO shops (shopId, car) VALUES ($shopId, $value)";
}
if you can only have 1 insert, which seems odd, then do something like:
$cars = "";
foreach ($_GET['cars'] as $value)
{
$cars .= $value . ",";
}
$cars = substr($cars,0,-1); //to remove the last comma
then
$ins = "INSERT INSERT INTO shops (shopId, car) VALUES ($shopId, $cars)";
you are going to end up with a field like 'honda,mazda,toyota' and this doesn't seem very efficient.
I have an array of checkboxes.
<input type="checkbox" name="selection[]" value="move" />
<input type="checkbox" name="selection[]" value="move2" />
<input type="checkbox" name="selection[]" value="move3" />
<input type="checkbox" name="selection[]" value="move4" />
Depending on the number of checkboxes selected, a table with corresponding number of rows is generated.
for($x=0; $x<$N; $x++)
{
echo nl2br("<td><textarea name=art[] rows=10 cols=30></textarea> </td><td><textarea name=science[] rows=10 cols=30></textarea></td></textarea></td><td><textarea name=method[] rows=10 cols=30></textarea></td><td><textarea name=criteria[] rows=10 cols=30></textarea></td></tr>");
}
I cannot tell how many table rows with corresponding columns will be generated each time. So how to write the code to insert each set of row array is a problem. I have tried the
$optionsVal = implode(",", $data);
but that only works to store the selected options and not for the generated table rows and columns.Please can anyone help with this. Thanks in advance
Okay so I think I understand a little better, but perhaps you should relay your question in other terms.
Basically my understanding is that you are accepting an uncertain (within the boundaries of the number of checkboxes you have) number of checkboxes, which there in turn generate a row for each selected check box.
If you want to store these generated rows in mySQL you need to post the data back to the database
$result = mysqli_query($query, $conn);
$row = mysqli_fetch_array($result);
You need to set a $result similar to this, and store your check box values in it
In this example if the end-user hits the save button it inserts the values from the check box into a variable
if(isset($_POST["savebtn"]))
{
//inserting the new information
$id = $_POST[""];
$name = $_POST[""];
//iterate through each checkbox selected
foreach($_POST["checkbox"] as $loc_id)
{
$query = "INSERT INTO table(ID, Loc_Code) VALUES('$id', '$loc_id')";
$result = mysqli_query($query, $conn);
}
?>
This was just kinda taken from another example, but you are way off with the implode, you need to save the results of the php selection to variables first, and then assign them rows in mySQL by looping through the selection
UPDATE:
Okay, so you got them in an array, seelction[] - this is good now you would want to check to see if a certain value is selected...
if (in_array("move2", $_POST['selection'])) { /* move2 was selected */}
then you want to put that into a single string - you were right with the implode method
echo implode("\n", $_POST['selection']);
then echo it out with a foreach loop
foreach ($_POST['selection'] as $selection) {
echo "You selected: $selection <br>";
}
I've searched extensively but can't find an answer… Hope someone can help:
I'm a newbie PHP and MySQL user and have a problem with checkboxes.
I have a simple HTML page which contains checkboxes.
The page is linked up to a MySQL db in PHPmyadmin.
The HTML is:
<html><p>User1<input type="checkbox" name="Users[]" id="Users1" value="1"/></p>
<p>User2<input type="checkbox" name="Users[]" id="Users2" value="2"/></p>
<p>User3<input type="checkbox" name="Users[]" id="Users3" value="3"/></p>
<p>User4<input type="checkbox" name="Users[]" id="Users4" value="4"/></p></html>
What I want is for the person filling in the form to check 1 or more of the values and then for the checked values to be displayed in PHPmyadmin, so that I can export them.
However, when using this PHP:
$values = implode(',', $_POST['Users']);
All I get in PHPmyadmin is "Array", and I can't figure out how to get the actual values to be displayed.
Thanks in advance,
You can get all value checked by looping :
$userChecked = $_POST['Users'];
for ($i=0; $i<count($userChecked ); $i++) {
echo( ($i+1) . ") " . $userChecked [$i] . "<br/>");
}
This will display all id. Instead of echo the value you can insert them in your database or do what you want. The values will be loop inside : $userChecked [$i]
#Daok: Yes, that displays the values
on the results page, but in
PHPmyadmin, it still indicates
"Array". How do I get it to display
the values?
PhpMyAdmin is just a tool to administrate php/mysql. I guess you mean that you have "array" written in your database? If you do want all value inside a field (varchar) than you just have to implode:
$comma_separated = implode(",", $_POST['Users']);
//Code here to Insert to you database with ...value($comma_separated)...
If you want 1 row for each entry :
$userChecked = $_POST['Users'];
for ($i=0; $i<count($userChecked ); $i++) {
//Insert Sql statement here with value($userChecked [$i])
}
try
$values = implode(',', (array)$_POST['Users']);
or
Users=array();
$values = implode(',', $_POST['Users']);