So I'm using a multiple checkboxs in a form and query the database with no problems. Now I want to add a dropdown list and combine it with the query with the checkboxs. When I run this I get a
Warning: Invalid argument supplied for foreach()
Here is my form
<form name="search_form" method="post" action="event_list">
<table>
<tr>
<td>Venue</td>
<td><input type="checkbox" name="check_list[]" value="AAC"><label >AAC</label><br />
<input type="checkbox" name="check_list[]" action="" value="AKC" id="check_list[]"/><label >AKC</label><br />
<input type="checkbox" name="check_list[]" action="" value="ASCA"/><label >ASCA</label><br />
<input type="checkbox" name="check_list[]" action="" value="CKE"/><label >CKE</label><br />
<input type="checkbox" name="check_list[]" action="" value="CPE"/><label >CPE</label><br />
<input type="checkbox" name="check_list[]" action="" value="DOCNA"/><label >DOCNA</label><br />
<input type="checkbox" name="check_list[]" value="NADAC"><label >NADAC</label><br />
<input type="checkbox" name="check_list[]" action="" value="TDAA"/><label >TDAA</label><br />
<input type="checkbox" name="check_list[]" action="" value="UKC"/><label >UKC</label><br />
<input type="checkbox" name="check_list[]" action="" value="UKI"/><label >UKI</label><br />
<input type="checkbox" name="check_list[]" action="" value="USDAA"/><label >USDAA</label><br />
</td>
</tr>
<tr>
<td style="text-align: left;">State:</td>
<td style="text-align: left;">
<select name="state" id="state" onChange="setCities();">
<option name="drop_down[]" value="Alabama">Alabama</option>
<option name="drop_down[]" value="Texas">Texas</option>
</select>
</td>
</tr>
<td align="right"><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>
Here is my PHP
<?php
$options = Array();
$options2 = Array();
foreach ($_POST['check_list'] as $check)
$options[] = 'venue=' . "'$check'";
foreach ($_POST['drop_down'] as $drop)
$options2[] = 'state=' . "'$drop'";
$sql = "SELECT * FROM venue_event_all";
if (count($options))
$sql .= " WHERE " . implode(' OR ', $options);
if (count($options2))
$sql .= " AND " . implode(' OR ', $options2);
$result=mysql_query($sql) or die(mysql_error());
?>
In a <select> input, the value of <option> is sent paired with the name of the select to POST/GET.
Setting a name on the option itself will not do anything. The dropdown value will still go with the name of the select.
You can check it by using this
echo $_POST['state'];
So, use this value to set into your query.
Edit : Obligatory - Please don't use MySQL as it is deprecated and not maintained by PHP any more. Use MySQLi, or PDO. Also, please sanitize your inputs before using them in the query. This is what happens when you don't.
foreach will show you error, if array is empty or is not set, so you need to check it first:
if(isset($_POST[0]) and count($_POST) > 0)
{
foreach...
}
I won't just rant about sql injection but give you a solution.
The only way to have your query safe with sensible amount of code is safeMysql library
(Based on Jeffrey code, not tested, but use in production freely):
<?php
include 'safemysql.class.php';
$db = new SafeMysql();
$options = array();
if (!empty($_POST['check_list'])) {
$options[] = $db->parse('venue IN (?a)', $_POST['check_list']);
}
if (!empty($_POST['drop_down'])) {
$options[] = $db->parse('state IN (?a)', $_POST['drop_down']);
}
$sql = "SELECT * FROM venue_event_all";
if ($options) {
$sql .= " WHERE " . implode(' AND ', $options);
}
$data = $db->getAll($sql);
Related
I'm making a form like this one:
<?php
echo '<tr>
<td><strong>Kamp</strong></td>
<td width="80px"><strong>1X2</strong></td>
<td><strong>Resultat</strong></td></tr>';
$no = 1;
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td>'.$row['kamp'].'</td>
<td><input type="radio" name="k1" id="k11" value="1" />1<input type="radio" name="k1" id="k1x" value="X" />X<input type="radio" name="k1" id="k12" value="2" />2</td>
<td><input name="k1r" type="text" id="k1r" placeholder="X-X" /></td>
</tr>
';
$no++;
}?>
And it echo a nice form with 3 rows from my database in the first <td>. It is like a betting-game, so I have the mathes in my database. But as it is right now, the user will check the radiobuttons at 3 different mathes, but submit the same, if you understand. How can I make it 3 different inputs?
I usually use counter in my loop
$no = 1;
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td>'.$row['kamp'].'</td>
<td><input type="radio" name="k1_'.$no.'" id="k11_'.$no.'" value="1" />1<input type="radio" name="k1_'.$no.'" id="k1x_'.$no.'" value="X" />X<input type="radio" name="k1_'.$no.'" id="k12_'.$no.'" value="2" />2</td>
<td><input name="k1r_'.$no.'" type="text" id="k1r_'.$no.'" placeholder="X-X" /></td>
</tr>
';
$no++;
if you want multiple input fields with the same name you can create an array of input values with brakets
<input type="radio" name="k1[]" id="k11" value="1" />
See: http://www.php.net/manual/en/faq.html.php#faq.html.arrays for more infomation.
I have tried out some code for dynamic insertion of data using array but the issue am facing is in a single row same data is been inserted and even if check box are left un-checked data value is inserted ignoring the checked value inside a "while-loop"..I am new to this array concept please help me out.
.php
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<div class="col-md-12">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
echo '
<tr>
<td align="left">' . $row['via'] . '<input type="hidden" name="type[]" value="' . $row['via'] . '"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>';
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
DB.php
<?php
session_start();
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(isset($_POST["submit"]) && isset($_POST["type"])){
//receiving post parameters
$types = $_POST["type"];
if(sizeof($types) > 0 ){
foreach($types as $type){
// create a new user profile
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$type."','".$type."','".$type."','".$type."', NOW())";
if(mysqli_query($con,$sql)){
header('Location: macro_ppl.php');
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}
}
}
?>
First of all checkbox values will not be present in the post if they are not set.
Second of all you add many results cause you call insert sql in the loop.
You can use:
var_dump($_POST['type']);
so you will see how the structure actually look like.
There are many ways to make this work one could be:
//setting the variables first
$ppl = 0;
$macro = 0;
$micro = 0;
$nano = 0;
//then run the loop to set them
foreach($types as $type){
if(in_array($type,['ppl','macro','micro','nano'])) //just to be sure nobody pass something else so we will not override other variables
$$type = 1;
}
//then write the query
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$ppl."','".$macro."','".$micro."','".$nano."', NOW())";
You are doing it wrong, just submit a form with data array
Form
<form id="form" name ="form" method = "POST" action="someForm.php">
<tr>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
</form>
someForm.php
if (isset($_POST['type'])) {
foreach ($_POST['type'] as $myType) {
echo $myType
}
}
Your Form
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
?>
<tr>
<td align="left"><?php echo $row['via'] ?><input type="hidden" name="type[]" value="<?php echo $row['via'] ?>"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
<?php
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
In PHP file
if (isset($_POST['submit'])) {
if(isset($_POST['type'])) {
foreach ($_POST['type'] as $value) {
echo $value;
/*add this in the query, this will return the value of checkbox which are checked*/
}
}
}
my form data im listed my table sample 10 records.
<td class='table-checkbox'><input type="checkbox" name="product[]" value="1" class='selectable-checkbox'></td>
<td><div class="input-mini">
<input type="text" id="spinnn" name="quantity[]" value="5" class='spinner'/>
</div>
</td>
</tr>
.....
.....
my php code
$carino = $_POST['carino'];
$quantity = $_POST['quantity'];
$product = $_POST['product'];
foreach($product as $product){
foreach($quantity as $quantity ){
$sql = "INSERT INTO mytable (product,quantity,cno) VALUES ('$product','$quantity','$carino')";
mysql_query($sql);
}}
i want to be insert this data my table. but my foreach is wrong how can i do ?
product is unique
my table
product - quantity - cno
1 5 2
2 10 2
http://pastie.org/private/nwrrinnxlrumt6p3kuyq#11,13-14,19
This:
<?php
if(isset($_POST['submit'])) {
$carino = "2";
$adet = $_POST['adet'];
$urunno = $_POST['urunno'];
$total = count($_POST['adet']);
echo '<hr>';
foreach ($urunno as $checked)
{
$value = $checked - 1;
echo "Value of Urunno: $checked: Adet: $adet[$value] <br>";
echo "INSERT INTO member_interests
(`urun`,`adet`,'carino')
VALUES
('$checked','$adet[$value]','$carino')<br>";
}
}
?>
<tr>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<td class='table-checkbox'><input type="checkbox" name="urunno[]" value="1">Product One</td>
<input type="text" id="spinnn" name="adet[]" class='spinner'/>
<td class='table-checkbox'><input type="checkbox" name="urunno[]" value="2">Product Two</td>
<input type="text" id="spinnn" name="adet[]" class='spinner'/>
<td class='table-checkbox'><input type="checkbox" name="urunno[]" value="3">Product Three</td>
<input type="text" id="spinnn" name="adet[]" class='spinner'/>
<td><div class="input-mini">
<input type="submit" name="submit" value="run" />
</form>
</div>
</td>
</tr>
</tbody>
</table>
</div>
Output:
Value of Urunno: 2: Adet: 2
INSERT INTO member_interests (`urun`,`adet`,'carino') VALUES ('2','2','2')
Value of Urunno: 3: Adet: 3
INSERT INTO member_interests (`urun`,`adet`,'carino') VALUES ('3','3','2')
The logic can be as follows (think of the code yourself, or search on the internet):
Make sure that all POST arrays are the same length (they should be)
Loop over the count from 0 to the length of the arrays
Insert the value at that point in each of the arrays into the database.
A quick tip: you are very susceptible to SQL injection. If this is production code, either use prepared queries, or use a PHP database wrapper like PDO to do it for you. The mysql_... functions are deprecated.
Try this one
<?php
//add the database connection
?>
<form name="myform" action="">
<table>
<?php
$length=//how many time below check box repeat in this page
for($i=0;$i<$length;$i++){?>
<tr>
<td class='table-checkbox'>
<input type="checkbox" name="urunno[]" value="<?php echo $i;?>" class='selectable-checkbox'>
</td>
<td>c1k</td>
<td>2147483647</td>
<td>520</td>
<td>435345345 A.Ş.</td>
<td>
<div class="input-mini">
<input type="text" id="spinnn" name="adet<?php echo $i;?>" class='spinner'/>
</div>
</td>
</tr>
<?php
}?>
</table>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_post['submit']))
{
$carino = $_POST['carino']; //here this element not present in question, i am also follow this
$adet = $_POST['adet'];
$urunno = $_POST['urunno'];
$length=sizeof($urunno);
for($i=0;$i<$length;$i++)
{
$urun1=$urunno[$i];
$adet1=$adet[$urun1];
$sql = "INSERT INTO table (urunno,adet,cno) VALUES ('$urun1','$adet1','$carino')";
mysql_query($sql);
//the above code insert sql work in every time //otherwise use batch insert
//refrer this link http://stackoverflow.com/questions/12960569/mysql-bulk-insert-via-php
}
}?>
By this code i can able insert the checkbox values to database. But i need add one column in phpmyadmin and in that column i need store the values like, if i select 2 checkbox, i need store that ckeckbox values in one column in another column i need store for selected checkbox as YES and unselected values as NO. But see i want both column
here is my code
<input type="checkbox" name="checkbox[]" value="Home" id="pageHome" onChange="toggleVisibility('home');" /><label for="pageHome"> Home</label><img id="home" src="images/icon-tick.png" style="visibility:hidden"/><br/>
<input name="checkbox[]" value="About_us" id="page_Aboutus" type="checkbox" onChange="toggleVisibility('aboutus');"><label for="page_Aboutus"> About Us</label><img id="aboutus" src="images/icon-tick.png" style="visibility:hidden" /><br/>
<input name="checkbox[]" value="Services" id="pageServices" type="checkbox" onChange="toggleVisibility('services');"><label for="pageServices"> Services</label><img id="services" src="images/icon-tick.png" style="visibility:hidden" /><br/>
<input name="checkbox[]" value="Products" id="pageProducts" type="checkbox" onChange="toggleVisibility('products');"><label for="pageProducts"> Products</label><img id="products" src="images/icon-tick.png" style="visibility:hidden"/><br/><br>
<input name="checkbox[]" value="Enquiry" id="pageEnquiry" type="checkbox" onChange="toggleVisibility('enquiry');"><label for="pageEnquiry"> Enquiry</label><img id="enquiry" src="images/icon-tick.png" style="visibility:hidden"/><br/><br>
<input name="checkbox[]" value="Contact_us" id="pageContact" type="checkbox" onChange="toggleVisibility('Contact');"><label for="pageContact">Contact Us</label><img id="Contact" src="images/icon-tick.png" style="visibility:hidden" /><br/>
php code
$required_pages = implode(',', $_REQUEST['checkBox']);
$sql="insert into request_quote(customer_name,organisation,phone_num,email,country,state,city,zipcode,project_type,website_url,website_purpose,website_keyword,Competitors,sample_websites,no_of_updation,required_pages,additional_page,other_details)
values('$customer_name','$organisation','$phone_num','$email','$country','$state','$city','$zipcode','$project_type','$website_url','$website_purpose','$website_keyword','$Competitors','$sample_websites','$no_of_updation','$required_pages','$additional_page','$other_details')";
mysql_query($sql) or die(mysql_error());
You can add a value='YES' attribute to each of your checkboxes.
Then make an array where you assume no checkbox has been checked. Because when we iterate later, only the checked checkboxes will be sent via $_REQUEST.
$checkBoxes['customer_name']="NO";
$checkBoxes['organisation']="NO";
$checkBoxes['phone_num']="NO";
$checkBoxes['email']="NO";
$checkBoxes['country']="NO";
$checkBoxes['state']="NO";
$checkBoxes['city']="NO";
$checkBoxes['zipcode']="NO";
$checkBoxes['project_type']="NO";
$checkBoxes['website_url']="NO";
$checkBoxes['website_purpose']="NO";
$checkBoxes['website_keyword']="NO";
$checkBoxes['Competitors']="NO";
$checkBoxes['sample_websites']="NO";
$checkBoxes['no_of_updation']="NO";
$checkBoxes['required_pages']="NO";
$checkBoxes['additional_page']="NO";
$checkBoxes['other_details']="NO";
// Only the checked checkboxes wil be itterated below.
// This will mean the $value would be YES no matter what.
// So I write it literal for SQL-Injection-security
foreach ($_REQUEST['checkbox'] as $checkboxName=>$value){
$checkBoxes[$checkBoxName]="YES";
}
And in your SQL-Query, replace the variables with items from the array.
I.E.
$sql="insert into request_quote(customer_name)
values('".$checkBoxes['customer_name']."')";
Security tip:
Also, directly inserting user input can be a huge security risk. Use mysql_real_escape_string($value) on all user-input-values you plan to use in a SQL-query.
You should look into $_POST. W3Schools will help you out: http://www.w3schools.com/php/php_forms.asp.
You have to use 3 tables, and relationate each other
table 1 -> customers (id, name, etc)
table 2 -> required_pages (id, name) - here you will add your options from checkbox (Home, About_us, etc)
table 3 -> customers_required_pages (id, customer_id, required_page_id)
When saving data, you will have to save sequentialy:
Your customer:
$sql = "INSERT INTO customers (field1, field2, fieldn...)"
$qry = mysql_query($sql);
Retrieve your customer Id:
$sql = "SELECT LAST_INSERT_ID() AS customerId";
$qry = mysql_query($sql);
$customerId = mysql_fetch_assoc($qry);
Save the relationship between customers and required_pages
<?php
foreach ($_REQUEST['checkBox'] as $oneCheckbox => $checkboxValue) {
$sql = "INSERT INTO customers_required_pages (customer_id, required_page_id) VALUES ({$customerId['customerId']}, '{$checkboxValue}')";
}
?>
When retrieving your data, you will select values from table2 using left join with table3, this way you will be able to know wich values where or not selected from the checkbox list
$sql = "SELECT rp.id, rp.name, IF(crp.customer_id IS NULL, 'NO', 'YES') AS checked FROM required_pages rp LEFT JOIN customers_required_pages crp ON rp.id = crp.required_page_id";
As an extra, consider use MySQLi or PDO instead of mysql as your database library, since the use of mysql lib has been discouraged
I was having the problem to store the multiple checkbox into the mysql table, but now it's working fine with this code:
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<?php
require("config.php");
?>
<?php
if(isset($_POST['submit'])){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$gender = $_POST['gender'];
$hobbies = implode(",",$_POST['hobbies']);
echo $hobbies;
$country = $_POST['country'];
// echo $hobbies;
//foreach($hobbies as $hobbies1){
//echo $hobbies1;
//$implode = implode(',',$hobbies1);
$sql = "INSERT INTO `userinfo`(`fname`,`lname`,`gender`,`hobbies`,`country`)
values('$fname','$lname','$gender','$hobbies','$country')";
//}
//$sql = "INSERT INTO `userinfo`(`fname`,`lname`,`gender`,`hobbies`,`country`)
// values('$fname','$lname','$gender','$hobbies1','$country')";
$query = mysql_query($sql) or die(mysql_error());
if
($query){
echo "<h1>Data inserted .. Happy coding</h1>";
}else{
echo "<h1>Please check the problem</h1>";
}
}
//}
?>
<form name="registration" method="post" action="">
<table border="1" cellpadding="2" cellspacing="2" align="center">
<tr>
<td>First Name:</td><td><input type="text" name="fname" required=""></td>
</tr>
<tr>
<td>Last Name:</td><td><input type="text" name="lname" required=""></td>
</tr>
<tr>
<td>Gender:</td><td><input type="radio" name="gender" value="male" required="">Male <input type="radio" name="gender" value="female" >Female</td>
</tr>
<tr>
<td>Hobbies:</td><td><input type="checkbox" name="hobbies[]" value="tennis">Tennis <br>
<input type="checkbox" name="hobbies[]" value="cricket">Cricket <br>
<input type="checkbox" name="hobbies[]" value="dance">Dance7 <br>
<input type="checkbox" name="hobbies[]" value="sketching">Sketching
</td>
</tr>
<tr>
<td>Country:</td>
<td>
<select name="country">
<option >----select----</option>
<option>India</option>
<option>Pakistan</option>
<option>UAE</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Register me"></td>
</tr>
</table>
</form>
</body>
</html>
I am trying to make this form with checkboxes get values 1 or 0, sort of a boolean, and UPDATE it on mysql, but I havent found a way yet. Maybe you can help. I'll post the form and the code that receives it. I am sure there might be a conflict of loops, but I tryed everything and couldnt get it working. Tks in advance.
THE FORM
<form action="esconde_cat.php" method="post">
<table width="300px" align="center" width="140" border="1">
<tr>
<td></td>
<td width="200">Categoria</td>
<td width="100">Mostrar</td>
</tr>
<?php
include "conecta.php";
include "verifica.php";
$sql = "SELECT * FROM categorias ORDER BY ordem";
$res = mysql_query($sql) or die (mysql_error());
while ($linha=mysql_fetch_array($res)) {
?>
<tr>
<td><input name="user[]" type="checkbox" value="true"/></td>
<td><?=$linha['1']; ?></td>
<td><?php if ($linha['3'] == TRUE){ echo 'SIM'; } else {echo 'NÃO'; } ?></td>
</td>
</tr>
<?php
}
?>
</table>
<br/>
<table align="center">
<tr>
<td>
<input type="submit" name="Delete" type="button" value="Alterar">
</td>
</tr>
</table>
</form>
THE CODE THAT RECEIVES THE FORM AND UPDATE MYSQL
<?php
include "conecta.php";
include "verifica.php";
\\THIS PART WORKS, GETS IF THE CHECKBOX IS CHECKED AND RECORD IT ON DB
if(isset($_POST['user'])) {
foreach ($_POST['user'] as $key => $read){
$read =(#$_POST['user']=='0')? $_POST['user']:'1';
echo $read;
$sql = "UPDATE categorias SET mostrar='$read' WHERE ordem='$key'";
$res = mysql_query($sql) or die ("Erro ao excluir") . mysql.error();
}
}
\\ON THIS PART OF THE CODE THAT I CANT GET THE VARIABLE TO GET THE
\\VALUE FROM CHEBOXES THAT ARE UNCHECKED RECORDED TO DATABASE
if (!isset($_POST['user'])) {
foreach ($_POST['user'] as $chave => $leia) {
$leia =(#$_POST['user']=='1')? $_POST['user']:'0';
echo $leia;
$sql = "UPDATE categorias SET mostrar='$leia' WHERE ordem='$chave'";
$res = mysql_query($sql) or die ("Erro ao excluir") . mysql.error();
}
}
?>
If a checkbox is left unchecked you will get NO key in the $_POST variable. If it's checked the key will be set and the value will be the value of the checkbox.
Assuming a name of "user[]" works, with something like:
<input type="checkbox" name="user[]" value="aa" />
<input type="checkbox" name="user[]" value="bb" checked="checked" />
<input type="checkbox" name="user[]" value="cc" checked="checked" />
<input type="checkbox" name="user[]" value="dd" />
<input type="checkbox" name="user[]" value="ee" checked="checked" />
You would expect $_POST to be:
array(
"user" => array(
"1" => "bb"
"2" => "cc"
"4" => "ee"
)
);