I have some simple PHP code that will generate new text boxes with the naming scheme of 'car_init$i' and 'car_num$i'. Where $i = 1 and I use i++ to increment it up. The problem I'm having is that while a user can have a maximum of 70 text boxes generated, it can be any number between 1 and 70. So I can have 46 text boxes as an example on a page if the user wanted just 46. So I would have car_num1, car_num2, car_init1, car_init2, etc. as my form names.
Car_ID would be my auto-incremented primary key, and I'd have 2 columns car_num and car_init. Is it possible to do something like this: INSERT INTO dbo (car_init, car_num) VALUES (car_init$i, car_num$i) and then use $i = 1 and i++ to increment it while adding all the values to new rows? Car_id = 1 would contain car_num1 and car_init1 information in their respective columns, Car_id = 2 would contain car_num2 and car_init2 information, and so on and so forth.
EDIT:
So this is the code I have now:
$car_num = $_POST["car_num"];
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
}
What happens is every time I add to my database, only the last thing I entered gets inputted. So if I have 3 cars needed, that's 6 text boxes, but only the last text boxes on the page are the ones that get inputted.
EDIT 2: This is how my text boxes are generated. All text boxes have it the way you said, using the 'car_init[]' and 'car_num[]'.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$i = 1;
while ($i <= $_POST['carAmount'] AND $i <= 70) {
// Now print the text box to the screen
echo "<b>$i</b>. Car Initial: <input type=\"text\" class='element text small' name=\"car_init[]\" maxlength='4' id='car_init[]' /> ";
echo "Number: <input type=\"text\" class='element text small' name=\"car_num[]\" maxlength='6' id='car_num[]' /><br>";
$i++;
}
}
Ah, I think I got it.
This is a problem:
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
}
I assume you're then running the query $sql? If so, that is running only the last value $sql contained! You need to:
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
// actually run the query!
}
Change your html to something like this:
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
Then in php, your variable will be an array!
$_POST['car_init'] // is an array!
Loop through those and do multiple INSERTs.
foreach ($_POST['car_init'] as $car_num => $car_init) {
// "INSERT INTO dbo (car_init, car_num) VALUES ('$car_init', $car_num)"
}
Edit based on your updates:
INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')"
Use PDO with prepared statements instead of using string interpolation. You seem to be susceptible to sql injection attacks.
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();
}
I am pretty stumped, I thought this would work for sure. I want to insert multiple checkbox values (if selected) into different columns of one table. I was attempting to do this with a for loop and keeping the naming convention consistent so I could utilize the for loop with the checkbox array. Here is php code:
$connection = new mysqli("localhost","root","","employee_db");
if(isset($_POST['check'])){
$check = $_POST['check'];
if($check){
print_r($check);
}else{
echo "nothing checked";
}
for($i=0;$i<sizeof($check);$i++){
$query = "INSERT INTO `checklist_test` (`$check[$i]`) VALUE (`\"$check[$i]\"`)";
$result = mysqli_query($connection,$query);
if(!$result){
die("NOPE <br>" . mysqli_error($connection));
}else{
echo "yup";
}
}
}
And here is the HTML
<form action="" method="post>
<input type="checkbox" name="check[]" value="check1">Check1
<input type="checkbox" name="check[]" value="check2">Check2
<input type="checkbox" name="check[]" value="check3">Check3
<input type="submit" value="submit">
</form>
The MySQL Columns are "id, check1, check2, check3" so SQL should look like:
INSERT INTO `checklist_test` (`id`, `check1`, `check2`, `check3`)
VALUES (NULL, 'test', 'test', 'test');
Appreciater outside P.O.V. that I need thanks!
If you the execute the query inside the loop, you would be executing x number of queries (or inserting x number of rows) rather than inserting into x number of columns. There is really no need to use a loop here since you have a set number of columns.
Use echo statements to print out the queries to see what you are running and you'll see why this isn't working.
You also should never put user input directly into a MySQL query. Read up on SQL injections.
I have two input fields:
<input type='hidden' name='amenId[]' value='$amen[amenId]'>
<input type="checkbox" name='amentities[]' id='check'>$amen[amenBG]
These two input fields are in foreach tag which loops through an array($amen). After the form is submitted I have php file that loops through the array and insert the id of the checked input and the value. Now the problem comes from the fact that my input fields are checkboxes. I have used this technic for different array where the input type was text and I didn't have problems. Here I have around 30 choices to choose from and when I check the first one and the fifth one in the database where the ids of the choicse should be 1 and 5 but instead of that are 1 and 2. I'm not sure why is that but I'm thinking that it has to do with getting the values only from the checked boxes.
My php code:
$checkedAmen = '';
foreach ($_POST['amentities'] as $key => $amen) {
$checkedAmen = $amen;
$checkedId = $_POST['amenId'][$key];
if ($checkedAmen == "on") {
$checkedAmen = "Yes";
}elseif($checkedAmen == "") $checkedAmen ="No";
$sqlAmen = "INSERT INTO ObjectAmen(ProductId, AmenId, AmenData) VALUES(?, ?, ?)";
if ($stmtAmen = $db -> prepare($sqlAmen)) {
$stmtAmen -> bind_param('iis', $last, $checkedId, $checkedAmen);
}else{
echo "Error: " . $db->error;
}
$stmtAmen -> execute();
}
Can someone help me? I would like to have the correct ids correspoding to the checked choices in the database.
There's nothing currently tying both of your inputs together. You can have a value on a checkbox though, so if it's checked you have the id
<input type="checkbox" name='amentities[]' value='$amen[amenBG]'>
Also you want to take id's off the input if it's in a foreach, because you'll be rebinding the id every time.
i have this two text fields that ask the user to put in two numbers that are limited to 49 numbers, so that i can have an array of number 1 to 50, or 151 to 200, or 27551 to 27600 any number but a series of 49 consecutive numbers, my problem is i dont know how to put them inside the database, i have no clue i have been searching for everything about inserting arrays but they dont work on my case,
This is my form
<form id="form3" name="form1" method="post" action="">
<p>From:
<input type="text" name="from" id="form_number" class="from" />
- To:
<input type="text" name="to" id="form_number" class="to" />
</p>
<p>Waybill Booklet:
<select name="waybill_booklet[]" id="form_list">
<?php
do {
?>
<option value="<?php echo $row_Booklet['id_waybill_booklet']?>"><?php echo $row_Booklet['booklet_no']?></option>
<?php
} while ($row_Booklet = mysql_fetch_assoc($Booklet));
$rows = mysql_num_rows($Booklet);
if($rows > 0) {
mysql_data_seek($Booklet, 0);
$row_Booklet = mysql_fetch_assoc($Booklet);
}
?>
</select>
</p>
<p>
<input type="hidden" name="status[]" value="4" />
<input type="submit" name="button" id="form_button" value="OK!" />
</p>
</form>
the 49 series of consecutive numbers will be inserted into the database with a foreign key what is chosen from the drop down menu, and a value of 4 that is in the hidden field, so basically there are 4 columns to my table 1 for primary key 1 for the series of numbers and 1 for the foreign key and the last will be the value of the numbers.
This is my php code to get the series of numbers
<?php
$booklet = $_POST['waybill_booklet'];
$status = $_POST['status'];
$from = $_POST['from'];
$to = $_POST['to'];
$number = range($from,$to);
$count = 0;
$myArray = range($from,$to);
while($count<=49){
if($count<49){
echo $myArray[$count]. ", ";
}else{
echo $myArray[$count];
}
$count++;
}
?>
i dont know how to insert the data's
$waybill = mysql_real_escape_string($_POST['waybill_booklet'][0]);
$status = mysql_real_escape_string($_POST['status'][0]);
foreach (range($from, $to) as $number) {
$sql = "INSERT INTO yourTable (id, waybill, status) VALUES($number, '$waybill', '$status')");
mysql_query($sql) or die(mysql_error());
}
You should also switch to PDO or mysqli, so you can use parametrized queries instead of substituting strings into the query. Then you don't need to escape the values like that.
Instead of storing this as an array (since you want to store this as bulk, I assume it will not involve any direct database level aggregation or computation), you can store it as a json string using the json_encode($myArray_series_of_numbers). This gives you the flexibility to store them as a string column and when you retrieve it back, you can use json_decode($model->series_of_numbers_column,true) to get it back as an array for easy computation back in PHP.
Hope this helps
Here is a tutorial on using mysql in php http://www.w3schools.com/php/php_mysql_insert.asp specifically the INSERT command. just build your data into variables instead of echo'ing it and then follow the guide to interact with a database
here is the auto increment tutorial to generate primary ids for each array element http://www.w3schools.com/sql/sql_autoincrement.asp
you can greatly increase the speed of the inserts and do it in one submit by building a multiple insert sql string.. and then using the insert guide above to run it.
INSERT INTO Table ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
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>";
}