Save multiple selected checkboxes in the database - php

i hope someone can help me. i have 4 checkboxes i want to save it in one string in my database,for example you only choose 2 or 3 checkboxes options.. the selected values only will save in one field of my database..
<tr>
<td><label>Plan Description:</label></td>
</table>
<?php
$des_query=mysql_query("SELECT * FROM addons;") or die ("Note: ". mysql_error());
?>
<?php
while($desc = mysql_fetch_array($des_query))
{
echo "<input type='checkbox' name='addons[]' value=".$desc['id'].">". $desc['name']."</input><br/>";
}
?>
</tr>

$insStr = '';
foreach($_POST['addons'] as $val){ $insStr .=$val.","; }
mysql_query("INSERT INTO promos (promo) VALUES ( '$insStr' )");

You can use serialize() method
example
$arr = Array ( [0] => 1 [1] => 2 [2] => 3);
$str = serialize($arr);
After retrieving from database use unserialize() method

You can take advantage of PHP built-in function named implode
Example
$checkboxValue implode(',',$_POST['addons']);

Try like this
if(!empty($_POST['addons'])) { $addons_string="";foreach($_POST['addons'] as $addon){$addons_string.=$addon.","; } }

test.php
<form name="test" action="test1.php" method="get">
<?php
for($i=0; $i<9;$i++){
echo "<input type='checkbox' name=a[] value=$i>$i<br>";
}
?>
<input type="submit" value="Submit">
</form>
and test1.php
<?php
foreach($_GET['a'] as $check) {
echo $check;
//SAVE VALUES TO DATABASE
}
?>
Hope it will help you

Related

Comparing only the selected value in loop to avoid error message

I am trying to build a basic quiz system.The following code shows how user choose the answer using radio butto and the getresult.php compares the radio input value with answer column. In my database there is a question, opt1, opt2, opt3, opt4, and answer columns.
<form method="POST" action="getresult.php">
<label>Enter Your Name:</label><br>
<input type="text" name="name"><br><br>
<?php
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("SELECT * FROM quiz");
$stmt->execute();
$result=$stmt->get_result();
echo "<form method='POST' action='getresult.php'>";
while($myrow = $result->fetch_assoc())
{
echo $myrow['id'];
echo ".";
echo $myrow['question'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt1'].">";
echo $myrow['opt1'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt2'].">";
echo $myrow['opt2'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt3'].">";
echo $myrow['opt3'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt4'].">";
echo $myrow['opt4'];
echo "<br><br>";
}?>
<input type="submit" name="submit" value="Get Results" class="btn btn-primary">
// getresult.php
<?php
extract($_POST);
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("SELECT * FROM quiz");
$stmt->execute();
$result=$stmt->get_result();
$submit=isset($_POST['submit']);
$count=0;
if($submit)
{
while($myrow = $result->fetch_assoc())
{
if($mycheck[$myrow['id']]==$myrow['answer'])
{
$count=$count+1;
}
}
echo "Hello ";
echo $_POST['name'];
echo "<br>";
echo "You scored ";
echo "$count";
}
Everything is correct, but if I do not select a radio button from a question, i.e if I leave the question it displays undefined offset error which is obvious but how can I not display that. OR how can I compare only chosen options?
You should try array_key_exists() like this:
if(array_key_exists($myrow['id'], $mycheck)
&& array_key_exists('answer', $myrow)
&& $mycheck[$myrow['id']]==$myrow['answer'])
{
$count=$count+1;
}
Or better yet, request your answers from database based on validated rows.
When the form is submitted, the chosen values are passed as (for example):
mycheck[1]=2
mycheck[2]=3
mycheck[3]=1
mycheck[4]=2
...etc. Now if you leave one question unanswered, let's say question 2, then no value will be submitted to the server for that question, so the submitted values could be something like this:
mycheck[1]=2
mycheck[3]=1
mycheck[4]=2
When PHP stores this in $_POST[], it will be an associative array:
$_POST['mycheck'] === array(
'1' => 2,
'3' => 1,
'4' => 2
)
With extract($_POST) you get the following value for $mycheck:
$mycheck === array(
'1' => 2,
'3' => 1,
'4' => 2
)
Now the following loop in your code will still go through all questions:
while($myrow = $result->fetch_assoc())
{
if($mycheck[$myrow['id']]==$myrow['answer'])
{
$count=$count+1;
}
}
But (in the example) the check for question 2 will fail, because $myrow['id'] will equal 2, while $mycheck[2] does not exist. This produces the undefined offset error.
As an unanswered question obviously should not increase the count, you could solve this issue as follows: first test if the question was answered (does $mycheck have an entry for it?), and only if that is the case, retrieve the answer from that entry:
while($myrow = $result->fetch_assoc())
{
$id = myrow['id'];
if(array_key_exists($id, $mycheck) && $mycheck[$id]==$myrow['answer'])
{
$count=$count+1;
}
}
For the above extra test you can use array_key_exists, or isset.
A bit rusted on PHP, but ...
Have you tried using the isset() function? Or changing the error reporting level appropriately?
http://php.net/manual/pt_BR/function.error-reporting.php
Why don't you create a new radio button "Don't know " which would be initially checked
<input type="radio" name="" checked>
So by default that button will be checked.

PHP passing Array

I have two php page.
In the first I have looping checkbox array :
<td><input type="checkbox" name="cek[]" value=" <?php echo "$kodeinventarisit" ?>"></td>`
Then i submit form from page one to page two :
<?php
include 'koneksi.php';
$cek = $_POST['cek'];
$jumlah_dipilih = count($cek);
for($x=0;$x<$jumlah_dipilih;$x++){
$jojo = $cek[$x];
$coba = "select * from msstok where kodeinventarisit = '$jojo' ";
$cobaquery = mysql_query($coba);
$hasil = mysql_fetch_array($cobaquery);
$jenis = $hasil['jenis'];
?>
<input name="kode" type="text" id="license" value="<?php echo htmlentities($jenis) ; ?>" readonly="readonly" />
<?php
echo "$jojo";
}
?>
The problem is in the sql query return nothing, I try echo "$jojo" and it's print the value but in the text field is empty..
Does anyone have suggestions on how to fix this?
Thank You Very Much
1
What you are doing is bad.
Load your data before your loop and loop every result to print them.
2
Protect your sql request from injection.
Connect
$db = new mysqli("","root","","");
Prepare your request
$sql = "select * from msstok where kodeinventarisit = ? ";
$res = $db->prepare($sql);
$res->bind_param("sssd",$jojo);
Get results
$res->execute();
Documentation : http://php.net/manual/fr/book.mysql.php
If you want to pass the array you need to check if arrive in you second page.
<pre>
print_r($_POST['cek']);
</pre>
Now, if arrive here, you can read the values like this:
<?php
// If is array(), then you can go to loop
if(is_array($_POST['cek']))
{
// Run the loop
foreach($_POST['cek'] as $value)
{
// Show values per line
echo $value. "<br/>";
}
}
?>
You can read only 1 value of your array
<?php echo $_POST['cek'][0]; ?>
<?php echo $_POST['cek'][1]; ?>
<?php echo $_POST['cek'][2]; ?>
Conclusion
You can't pass array to SQL in query. If you want to use it, this is the only way with implode.
$coba = "SELECT * FROM msstok WHERE kodeinventarisit IN (".implode(',', $jojo).")";
$records = mysql_query($coba, $connection);
while ($row = mysql_fetch_array($records)) {
echo "Name: " . $rows['name'] . "<br />"; // replace the name for column you want
}

PHP Select List - Insert multiple values in database

I'm trying to insert multiple values in the database using select list. What I got so far:
HTML
<form enctype="multipart/form-data" action="" method="post">
<select name="cars[]" multiple="multiple" style="width:300px">
<?php
$getcars = mysql_query("SELECT cars_id, cars_name FROM car");
while ($row = mysql_fetch_assoc($getcars)) {
$car_id = $row['cars_id'];
$car_name = $row['cars_name'];
?>
<option value="<?php echo $car_id ?>"><?php echo $car_name ?></option>
<?php } ?>
</select><br />
<input type="submit" name="submit" value="Submit"/><br/>
</form>
PHP
$cars= $_POST['cars'];
echo $cars;
for($i = 0; $i < count($cars); $i++){
echo $cars[$i];
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
}
Unfortunately it doesn't work, I tried to print $cars to check the resulted value. It prints "Array", and when I tried to print $cars[$i] it prints nothing.
Does anyone know what the problem is?
There is an extra closing bracket that should be removed. You are not checking if your query was successful or not.
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
should be:
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]')") or die(mysql_error());
Since $cars is an array, you can print its content using print_r or var_dump:
print_r($cars);
var_dump($cars);
Useful reading:
How to get useful error messages in PHP?
mysql_* functions are deprecated
You have error $cars[$i]] and need change $cars[$i]
$carGroups = mysql_query("INSERT INTO car_groups VALUES('$company','$cars[$i]]')");
fix php for you with good sql
$cars= $_POST['cars'];
echo $cars;
foreach($cars as $i => $cars_name){
echo $cars_name;
$carGroups = mysql_query("INSERT INTO car_groups SET `fieldcompany`='{$company}', `fieldcars`='{$cars_name}'");
}

Two values from an array checkbox

So I have a mysql table for the charges of a hospital. My program currently only gets the price of the checked procedure. But now, I also want to get the procedure name when it is checked.
transaction.php
while($row = mysql_fetch_array($result))
{
echo ' <tr> <td>'.$row[0].'</td> <td>'.$row[1].'</td><td>'.$row[2].'</td>';
$procedure=$row['procedure'];
echo '<td><input type="checkbox" name="er[]" value="$price."|".$procedure"></td>';
echo "</tr>";
}
echo '</table>';
computation.php
<?php
if(isset($_POST['er']))
{
$ercharge=$_POST['er'];
$totalofer = array_sum($ercharge);
}
if(isset($_POST['ultrasound']))
{
$x=$_POST['ultrasound'];
$totalofultrasound = array_sum($x);
}
if(isset($_POST['confinement']))
{
$y=$_POST['confinement'];
$totalofconfinement = array_sum($y);
}
$total = $totalofer + $totalofultrasound + $totalofconfinement;
$p = explode("|", $ercharge);
echo $p;
echo $total;
?>
It only gets the row for price. Can the value attribute have two values? I can't just make another checkbox cause that would be inappropriate.
edit: the explode function doesnt work. It says: Warning: explode() expects parameter 2 to be string, array given in C:\xampp\htdocs\computation.php on line 18
You should split your parameters in the HTML:
echo '<td><input type="checkbox" name="checked[$row_index][]" value="1">';
echo '<input type="hidden" name="prices[$row_index][]" value="$price">';
echo '<input type="hidden" name="procedures[$row_index][]" value="$procedure"></td>';
where $row_index is incremented on each row (tr tag)
By the way, explode will work on the items of the er array, not on the array itself. Try:
foreach ($er as $item) {
var_dump( explode( "|", $item ) );
}
I'm not sure I understand your question but couldn't you set the name attrtibute for your checkbox to the name of the procedure? It looks like you are setting the name to the er[] array but you never reference that later.

inserting checkbox values to database

I have a php form with some textbox and checkboxes which is connected to a database
I want to enter all the details into the database from the form.All the textbox values are getting entered except the checkbox values.I have a single column in my table for entering the checkbox values and the column name is URLID.I want to enter all the selected checkbox(URLID)values to that single column only ,separated by commas.I have attached the codings used.can anyone find the error and correct me?
NOTE: (The URLID values in the form is brought from the previous php page.those codings are also included.need not care about it)
URLID[]:
<BR><?php
$query = "SELECT URLID FROM webmeasurements";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
$URLID = $row[0];
echo "<input type=\"checkbox\" name=\"checkbox_URLID[]\" value=\"$row[0]\" />$row[0]<br />";
$checkbox_values = implode(',', $_POST['checkbox_URLID[]']);
}
?>
$URLID='';
if(isset($_POST['URLID']))
{
foreach ($_POST['URLID'] as $statename)
{
$URLID=implode(',',$statename)
}
}
$q="insert into table (URLID) values ($URLID)";
You really should separate your model from the view. It's 2011, not 2004 ;o
if (isset($_POST['checkbox_URLID']))
{
// Notice the lack of '[]' here.
$checkbox_values = implode(',', $_POST['checkbox_URLID']);
}
$URLIDs = array();
while($row = mysql_fetch_row($result))
{
$URLIDs[] = $row[0];
}
foreach ($URLIDs as $id)
{
?>
<input type="checkbox" name="checkbox_URLID[]" value="<?php echo $id; ?>" /><?php echo $id; ?><br />
<?php
}
?>
<input type="submit"/>

Categories