Multiple checkbox in php html - php

I have a form in html like this, but it's error for checkbox question, someone please help me solve my problem.
It's multiple checkbox in multiple question
if(empty($tampil_pertanyaan)){
echo "<tr><td colspan=\"6\">Data tidak tersedia</td></tr>";
}else{
$no = 1; //for question
$no2 = 0; //for array
foreach($tampil_pertanyaan as $row)
{
<input type="hidden" name="user[]" id="user[]" value="<?php echo $data["user"]; ?>">
<tr>
<td><input type="checkbox" class="w3-check" name="ket_jawaban[<?php echo $no2;?>]" id="ket_jawaban[<?php echo $no2;?>]" value="<?php echo $row->pil1;?>" oninput="this.className = ''"></td>
<td> <?php echo $row->pil1;?></td>
</tr>
<tr>
<td><input type="checkbox" class="w3-check" name="ket_jawaban[<?php echo $no2;?>]" id="ket_jawaban[<?php echo $no2;?>]" value="<?php echo $row->pil2;?>" oninput="this.className = ''"></td>
<td> <?php echo $row->pil2;?></td>
</tr>
<tr>
<td><input type="checkbox" class="w3-check" name="ket_jawaban[<?php echo $no2;?>]" id="ket_jawaban[<?php echo $no2;?>]" value="<?php echo $row->pil3;?>" oninput="this.className = ''"></td>
<td> <?php echo $row->pil3;?></td>
</tr>
$no++;
$no2++;
}
And i my controller (i use Codeigniter)
public function insert_jawaban(){
// Proses pemvalidasian data yg di input
$this->form_validation->set_rules('ket_jawaban[]', 'ket_jawaban', 'trim|xss_clean');
if ($this->form_validation->run() == FALSE){
echo validation_errors(); // tampilkan apabila ada error
}else{
//Insert ke tabel jawaban
$result = array();
foreach($_POST['ket_jawaban'] AS $key => $val){
$result[] = array(
"id_jawaban" => '',
"user" => $_POST['user'][$key],
"ket_jawaban" => $_POST['ket_jawaban'][$key]
);
}
$res = $this->db->insert_batch('jawaban', $result);
}
why every time it returns one value, even though I checked three.
Firstly I apologize if there is any wrong in my question is because I am newbie here.
Thanks and please advise.

Related

i am trying to update my data with an image updation too but the image isset would not work in php

Hey guys i have created a register form with an image upload too but when i try to update this form i try to get the id but the isset of my image is not working so it just wont run my update query do check it out
this is the updation form where all the values will be displayed for edit now can i run the update function in the isset condition of my submit button and then update the data
<title>Register Update</title>
<?php
//error_reporting(0);
$id=$_GET['id'];
function __autoload($classname)
{
include "$classname.php";
}
$obj = new connect();
$st=$obj->con();
if (isset($_POST['sub']))
{
$upd= new update();
$upd->updatedata($_POST);
}
$qry = "select * from register ";
$run = mysqli_query($st,$qry);
$row = mysqli_fetch_assoc($run);
{
$g = $row['gen'];
$l = $row['lang'];
}
$query=mysqli_query($st,"select * from register where id='$id'");
//echo "<ul>";
while($query2=mysqli_fetch_assoc($query))
{
//print_r($query2);
echo "<form method='POST' action='RegisterRetrieve.php'>";
echo "<table>";
?>
<p><input type="hidden" name="sid" value="<?php echo $query2['id']; ?>"></p>
<tr>
<td>
First Name:
</td>
<td><input type="text" name="uname" value="<?php echo $query2['uname']; ?>"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pwd" value="<?php echo $query2['pwd']; ?>"></td>
</tr>
<tr>
<td>Email Id:</td>
<td><input type="text" name="emailid" value="<?php echo $query2['emailid']; ?>"
</td>
</tr>
<tr>
<td>Radio Button: Are you male or female?</td>
<?php
if ($g == "male"){
echo "<td><input type='radio' name='gen' value='Male' id='gen' checked> Male <input type='radio' name='gen' value='Female' id='gen'> Female </td>";
}
else
{
echo "<td><input type='radio' name='gen' value='Male' id='gen'> Male <input type='radio' name='gen' value='Female' id='gen' checked> Female </td>";
}
?>
</tr>
<tr>
<td>Check Box: Check the languages you know?</td>
<td><?php
$lang=explode(',',$l);
//print_r($lang);
if(in_array('Cricket', $lang))
echo '<input type="checkbox" name="lang[0]" value="Cricket" checked>Cricket';
else
echo '<input type="checkbox" name="lang[0]" value="Cricket">Cricket';
if(in_array('Basketball', $lang))
echo '<input type="checkbox" name="lang[1]" value="Basketball" checked>Basketball';
else
echo '<input type="checkbox" name="lang[1]" value="Basketball">Basketball';
if(in_array('Hockey', $lang))
echo '<input type="checkbox" name="lang[2]" value="Hockey" checked>Hockey';
else
echo '<input type="checkbox" name="lang[2]" value="Hockey">Hockey'."<br>";
?>
</td>
</tr>
<tr>
<td>Mobile No:</td>
<td><input type="text" name="mobile" value="<?php echo $query2['mobile']; ?>"
</td>
</tr>
<tr>
<td>10th Marks:</td>
<td><input type="text" name="marks_10" value="<?php echo $query2['10marks'];?>"
</td>
</tr>
<tr>
<td>
12th Marks:</td>
<td><input type="text" name="marks_12" value="<?php echo $query2['12marks'];?>"</td>
</tr>
<tr>
<td>
Browse Image:</td>
<td><input type="file" name="file1"></td>
<td><img src='img/<?php echo $query2['name'];?>' width='150px' height='150px'></td>
</tr>
<tr>
<td>
<select name="priority">
<option value="admin">
admin
</option>
<option value="<?php echo $query2['priority']; ?>"><?php echo $query2['priority']; ?>
</option>
<option value="superadmin">
superadmin
</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="submit" name="sub"><br>
</td>
</tr>
<?php
echo "<table>";
echo "</form>";
}
//echo "</ul>";
?>
now my update query which i m using but when i try to isset my image it just wont go in that condition
<?php
class update extends connect
{
function updatedata($rel)
{
$obj= new connect();
$obj->con();
extract($_POST);
$id=$_GET['id'];
$line = implode("," ,$lang);
print_r($_POST);
if(isset($_FILES["file1"]))
{
extract($_POST);
echo "hello";
$name = $_FILES['file1']['name'];
$type = $_FILES['file1']['type'];
$size = $_FILES['file1']['size'];
$tmp_name = $_FILES['file1']['tmp_name'];
$loc = 'img/';
$ext = substr($name,strpos($name,'.')+1);
if($_FILES['file1']['size']>= '10000' || $_FILES['file1']['size']<="23000000")
{
//echo $size;
}
else{
// echo "size is not supported";
}
$val = $_FILES['file1']['size'];
if($ext == 'jpg' || $ext == 'png')
{
//echo $lang;
//print_r($_POST);
//exit;
$val =("update register set uname='$uname',pwd='$pwd',emailid='$emailid',gen='$gen',lang='$line',mobile='$mobile',10marks='$marks_10',12marks='$marks_12' file1='$name' where id=$sid");
//print_r($qry);
$res=mysqli_query($this->con(),$val);
//print_r($run);
if($res)
{
move_uploaded_file($tmp_name,$loc.$name);
//echo "data saved";
//echo "Data inserted";
}
else
{
//echo "Data Not Inserted";
}
}
}
}
//print_r($val);
// return $res;
}
?>
Your html is broken:
</tr>
<?php
echo "<table>"; <--shouldn't this be </table>?
echo "</form>";
}

PHP Variable changes its own value on equal loops

I have a variable putting out the coordinates of a address. I am printing the coordinates before the name to test at the moment. On odd number loops (it is in a foreach loop) it works fine, putting the variable in the data-latLng attribute. While on Even number loops it gives out different values - not coordinates. values like: 2 and ..
Here is what I mean:
An odd numbered loop would print this out:
Meanwhile on an even loop number, the data-latLng attribute puts out different values:
Here is the code:
$area_lat_long = isset($area_lat_long[$mapCounter])?$area_lat_long[$mapCounter]:"-26.2041028, 28.047305100000017";
echo $area_lat_long;
echo '<strong>area: '. $streetAdd[$count] .' <a class="glyphicon glyphicon-new-window" type="button" data-toggle="modal" data-target="#mapModal" data-latLng="'. $area_lat_long .'" style="cursor:pointer;"></a><br>';
$mapCounter++;
The PHP code runs above the table code, the code above gives the line of the coordinates and then the area.
As you can see, the $area_lat_long gives coordinates before every area, but when using the EXACT same variable for the data-latLng it changes on even loops?
Edit
To the guys who wanted the whole loop in the comments:
foreach ($streetAdd as $key){
print_r($area_lat_long);
//LAT LONG
$area_lat_long = isset($area_lat_long[$count])?$area_lat_long[$count]:"-26.2041028, 28.047305100000017";
echo $area_lat_long;
echo '<strong>area: '. $streetAdd[$count] .' <a class="glyphicon glyphicon-new-window" type="button" data-toggle="modal" data-target="#mapModal" data-latLng="'. $area_lat_long .'" style="cursor:pointer;"></a><br>';
$mapCounter++;?>
<input type="hidden" id="street_address" name="street_address[<?php echo $count; ?>]" value="<?php echo $streetAdd[$count];?>">
<table class="table table-striped">
<thead>
<tr>
<th>Media Type</th>
<th>Quantity Required</th>
<th>Average Asset Price</th>
<th><!-- Remaining Total --></th>
<th>More Options</th>
</tr>
</thead>
<tbody class="assetCounter">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php
$j = 0;
$total_used = 0;
$total_bal = isset($budget)?$budget:0;
$qty = 1;
$i = 0;
foreach ($my_categories as $key) { //loop thru chosen media types
foreach ((array)$key as $data) {
// print_r($data);
//check valid description
$j++;
$data_description = isset($data->mec_description)?$data->mec_description:'';
$latitude_longitude = explode(",",$area_lat_long); //print_r($latitude_longitude);
$latitude = $latitude_longitude[0];
$longitude = isset($latitude_longitude[1])?$latitude_longitude[1]:$latitude;
//pricing
$min_price = isset($data->asg_min_price)?$data->asg_min_price:0;
$max_price = isset($data->asg_max_price)?$data->asg_max_price:0;
$average_p = ($min_price + $max_price)/2;
$total_used += $average_p;
$total_bal -= $average_p;
if($total_bal < 0){
$total_bal = 0;
}
if($average_p == 0){
$title = "Pricing information not yet available from Media Owners";
} else {
$title = "NOTE: These are just estimates/guidelines, latest pricing information will be received from Media Owners quotations";
}
?>
<tr class="asset_<? echo $counterForAsset; ?>">
<td><?php
echo strtoupper($mec_stuff[$i]);
?>
<input type="hidden" id="media_category" name="mec_id[]" value="<?php
foreach($mec_stuff as $ms) {
echo $ms . ',';
}
?>">
<input type="hidden" id="media_category" name="media_category[]" value="<?php echo $data_description; ?>"></input></td>
<td><input type="text" class="form-control q_asset_<? echo $counterForAsset; ?> med_quantity" name="med_quantity[]" id="med_quantity" placeholder="Quantity Required" value="1"/></td>
<td><input type="text" readonly="true" name="avg_total[]" id="asset_<? echo $counterForAsset; ?>" class="form-control avg_asset_<? echo $counterForAsset; ?>" value="<?php echo number_format($total_bal,2); ?>" title="<?php echo $title;?>"/></td>
<!-- <td><input type="text" readonly="true" name="avg_total[]" id="avg_total--><?php //echo $j; ?><!--" class="form-control asset_--><?// echo $i; ?><!--" value="--><?php //echo number_format($total_bal,2); ?><!--" title="--><?php //echo $title;?><!--"/></td>-->
<td><input type="text" readonly="true" name="rem_total[]" id="asset_<? echo $counterForAsset; ?>" class="form-control rem_asset_<? echo $counterForAsset; ?>" value="<?php echo number_format($total_bal,2); ?>"/></td>
<!-- <td><input type="text" readonly="true" name="rem_total[]" id="rem_total--><?php //echo $j; ?><!--" class="form-control --><?// echo $i; ?><!-- asset_--><?// echo $i; ?><!--" value="--><?php //echo number_format($total_bal,2); ?><!--"/></td>-->
<td><?php echo "<a class='js-fire-modal btn btn-info' type='button' data-toggle='modal' data-mecid='$mec_stuff[$i]' href='#' name='size_button' onclick=\"sizeModal2(1, $j, '$latitude','$longitude','$description')\">>>></a>";?></td>
</tr>
<tr>
<td></td>
<td colspan="4" id="<?php echo $j; ?>"></td>
</tr>
<?php $i ++; $counterForAsset++; }
}?>
<tr>
<td> </td>
<td> <input type="hidden" id="hidSubtotal<?php echo $j;?>" value="<?php echo number_format($total_used,2); ?>"></td>
<td> Subtotal</td>
<td> <span id="lblSubtotal<?php echo $j; ?>"><?php echo number_format($total_used,2); ?></span> </td>
</tr>
</tbody>
</table>
<?php $count++;
}
foreach($a as $b) {
$x = isset($x[$c]) ? $x[$c] : "foo7";
echo $x;
}
Let us "run" that piece of code, assuming
$x = array('c' => 'lat,lng');
before the loop.
So loop #1 prints 'lat,lng'.
Loop #2 checks if isset('lat,lng'[$c]), evaluates to false, so $x will be 'foo'.
'foo' will be printed.
Loop #3 does the same as #2, but checks if isset('foo'[$c]), again evaluating to false.
Again 'foo' will be printed.
That's the reason.
I don't know what else you are doing outside that loop and most of the code seems to do nothing or nothing intended really.

check the checkbox if the data is same with database

Cannot find out what problems,for example at the beginning i add patient details, i selected allergies and asthma and store into database,but i want to edit the details, it only checked asthma (last value)...please help me find out the answer Thank you.
<tr>
<td>Past Medical Records</td>
<td><?php
$DiseaseSplit = $medicalRec['Diseases'];
$array = explode(", ",$DiseaseSplit);
foreach ($array as $item) {
echo "<li>$item</li>";
}
?></td></tr>
<tr><label class="q" for="q1"></label>
<td><input name="q1[]" type="checkbox" value="NONE" <?php if($item == "NONE") { echo 'checked=\"checked\"';}?>>None</td></tr>
<tr>
<td><input name="q1[]" type="checkbox" value="ALLERGIES" <?php if($item == "ALLERGIES") { echo 'checked=\"checked\"';}?>>Allergies</td>
<td align="left"><input name="q1[]" type="checkbox" value="BLOOD DYSCRASIAS" <?php if($item == "BLOOD DYSCRASIAS") { echo 'checked=\"checked\"';}?>>Blood Dyscrasias</td></tr>
You're overwriting $item for every iteration of the loop.
I would try making a hash map to see which values should be shown/hidden:
<tr>
<td>Past Medical Records</td>
<td><?php
$data = array();
$DiseaseSplit = $medicalRec['Diseases'];
$array = explode(", ",$DiseaseSplit);
foreach ($array as $item) {
$data[$item] = true;
echo "<li>$item</li>";
}
?></td></tr>
<tr><label class="q" for="q1"></label>
<td><input name="q1[]" type="checkbox" value="NONE" <?php if(isset($data["NONE"])) { echo 'checked=\"checked\"';}?>>None</td></tr>
<tr>
<td><input name="q1[]" type="checkbox" value="ALLERGIES" <?php if(isset($data["ALLERGIES"])) { echo 'checked=\"checked\"';}?>>Allergies</td>
<td align="left"><input name="q1[]" type="checkbox" value="BLOOD DYSCRASIAS" <?php if(isset($data["BLOOD DYSCRASIAS"])) { echo 'checked=\"checked\"';}?>>Blood Dyscrasias</td></tr>

saving data from an array without submitting any form php

I'm tryng to save an array so I have the following code:
<?php
$sql = "SELECT * FROM scenarii where code_s='".mysql_real_escape_string($_POST['code_s'])."'";
$qry = mysql_query($sql) or die(__LINE__.mysql_error().$sql);
$i = -1; // index des enregistrements
?>
<table cellpadding="5" cellspacing="5">
<tr>
<td><strong>CODE SCENARIO</strong></td>
<td><strong>LIBELLE</strong></td>
<td><strong>ACTION</strong></td>
<td><strong>DESCRIPTION</strong></td>
<td><strong>DATE</strong></td>
</tr>
<form action="<?php echo (isset($_POST['go'])) ? 'go.php' : '#'; ?>" method="post">
<input type="hidden" name="liasse" value="<?php echo $_POST['liasse']; ?>"/>
<input type="hidden" name="n_doss" value="<?php echo $_POST['n_doss']; ?>"/>
<input type="hidden" name="qualite" value="<?php echo $_POST['qualite']; ?>"/>
<?php while($row = mysql_fetch_assoc($qry)): ?>
<tr>
<td><input name="data[<?php echo ++$i; ?>][code_s]" type="text" value="<?php echo $row['code_s'];?>" size="10"></td>
<td><input name="data[<?php echo $i; ?>][titre]" type="text" value="<?php echo $row['titre']; ?>" size="45"></td>
<td><input name="data[<?php echo $i; ?>][action]" type="text" value="<?php echo $row['action']; ?>" size="15"></td>
<td><input name="data[<?php echo $i; ?>][libelle]" type="text" value="<?php echo $row['libelle']; ?>" size="55"></td>
<td><input type="text" name="data[<?php echo $i; ?>][date]" value="<?php echo $get_date($row['jour']) ; ?>" size="12"></td>
</tr>
<?php endwhile; ?>
And in order to save this I have this code:
if (isset($_POST['liasse'])) {
$value = $_POST['data'] ;
foreach($value as $key => $array)
{
$sql = 'INSERT INTO agenda SET
liasse = "'.mysql_real_escape_string($_POST['liasse']).'",
code_s = "'.mysql_real_escape_string($array['code_s']).'",
date_action = "'.date('Y-m-d',strtotime($array['date'])).'",
libelle = "'.mysql_real_escape_string($array['titre']).'",
action = "'.mysql_real_escape_string($array['action']).'",
description = "'.mysql_real_escape_string($array['libelle']).'",
n_doss = "'.mysql_real_escape_string($_POST['n_doss']).'",
qualite = "'.mysql_real_escape_string($_POST['qualite']).'"
';
mysql_query($sql) or die(__LINE__.mysql_error().$sql);
}
But I'm really lost,
In fact I use a form for that, now I would like to submit all of this data but without any form, directly when I have the first while I would like to save it.
The thing is that I'm lost because I can not call any var like that data[][code_s].
So I do not know how to save this. I would like to save it in background, and not to display that something has been saved.
Receive all my Utmost Respect
kind regards,
SP.
Wrap the code od the lower code block into a function and hand over the value array as argument:
function storeValues ($data) {
foreach($data as $key => $val)
{
$catalog=sprintf("%s='%s'",$key,$val);
$sql = sprintf('INSERT INTO agenda SET %s', implode(',',$catalog));
mysql_query($sql) or die(__LINE__.mysql_error().$sql);
} // foreach
} // function storeValues
You call this function when you want to save the values. So after retrieving them from the database. You call it for each row you retrieve and hand over the values like that:
storeValues ($row);
This will store one row of values at a time. Obviously this can be optimized to use a multiple insert. But let's take one step after another...

PHP Form checkbox question

I have a form that takes the following inputs:
Name: IBM
Surface(in m^2): 9
Floor: (Checkbox1)
Phone: (Checkbox2)
Network: (Checkbox3)
Button to send to a next php page.
All those values above are represented in a table when i press the submit button.
The first two (name and surname) are properly displayed in the table.
The problem is with the checkboxes. If i select the first checkbox the value in the table should be presented with 1. If its not selected the value in the table should be empty.
echo "<td>$Name</td>"; // works properly
echo "<td>$Surface</td>"; // works properly
echo "<td>....no idea for the checkboxes</td>;
Some part of my php code with the variables:
<?php
if (!empty($_POST))
{
$name= $_POST["name"];
$surface= $_POST["surface"];
$floor= $_POST["floor"];
$phone= $_POST["telefoon"];
$network= $_POST["netwerk"];
if (is_numeric($surface))
{
$_SESSION["name"]=$name;
$_SESSION["surface"]=$surface;
header("Location:ExpoOverzicht.php");
}
else
{
echo "<h1>Wrong input, Pleasee fill in again</h1>";
}
if(!empty($floor) && ($phone) && ($network))
{
$_SESSION["floor"]=$floor;
$_SESSION["phone"]=$phone;
$_SESSION["network"]=$network;
header("Location:ExpoOverzicht.php");
}
}
?>
Second page with table:
<?php
$name= $_SESSION["name"];
$surface= $_SESSION["surface"];
$floor= $_SESSION["floor"];
$phone= $_SESSION["phone"];
$network= $_SESSION["network"];
echo "<table class=\"tableExpo\">";
echo "<th>name</th>";
echo "<th>surface</th>";
echo "<th>floor</th>";
echo "<th>phone</th>";
echo "<th>network</th>";
echo "<th>total price</th>";
for($i=0; $i <= $_SESSION["name"]; $i++)
{
echo "<tr>";
echo "<td>$name</td>"; // gives right output
echo "<td>$surface</td>"; // gives right output
echo "<td>...</td>"; //wrong output (ment for checkbox 1)
echo "<td>...</td>"; //wrong output (ment for checkbox 2)
echo "<td>...</td>"; //wrong output (ment for checkbox 3)
echo "<td>....</td>";
echo "</tr>;";
}
echo "</table>";
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="form1">
<h1>Vul de gegevens in</h1>
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" size="18"/></td>
</tr>
<tr>
<td>Surface(in m^2):</td>
<td><input type="text" name="surface" size="6"/></td>
</tr>
<tr>
<td>Floor:</td>
<td><input type="checkbox" name="floor" value="floor"/></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="checkbox" name="phone" value="phone"/></td>
</tr>
<tr>
<td>Network:</td>
<td><input type="checkbox" name="network" value="network"/></td>
</tr>
<tr>
<td><input type="submit" name="verzenden" value="Verzenden"/></td>
</tr>
</table>
There might be a few spelling mistakes since i had to translate it.
Best regards.
Instead of directly assigning your checkbox variables, see if they have been checked or not first.
$verdieping = isset($_POST["floor"]) ? $_POST["floor"] : 0;
$telefoon = isset($_POST["telefoon"]) ? $_POST["telefoon"] : 0;
$netwerk = isset($_POST["netwerk"]) ? $_POST["netwerk"] : 0;
This way, if the user hasn't ticked a checkbox, you have a value of '0' assigned to it instead of an undefined variable.
If you declare a checkbox with:
<input type="checkbox" name="mycheckbox" value="1">
you can check the value after submitting the form by:
if(!empty($_POST["mycheckbox"])) {
// checkbox was checked
}
else {
// checkbox was not checked
}
In this php page you can write like this, it may be solution of your question
if (!empty($_POST))
{
$standnaam = $_POST["name"];
$oppervlakte = $_POST["surface"];
$verdieping = $_POST["floor"];
$telefoon = $_POST["telefoon"];
$netwerk = $_POST["netwerk"];
if (is_numeric($oppervlakte))
{
$_SESSION["name"]=$standnaam;
$_SESSION["surface"]=$oppervlakte;
header("Location:ExpoOverzicht.php");
}
else
{
echo "<h1>Wrong input, Pleasee fill in again</h1>";
}
if(!empty($verdieping) && ($telefoon) && ($netwerk))
{
$_SESSION["floor"]=$verdieping;
$_SESSION["phone"]=$telefoon;
$_SESSION["network"]=$netwerk;
header("Location:ExpoOverzicht.php");
}
}

Categories