two arrays in one form to mysql with php - php

I have a form with two fieldsets which contains checkboxes:
<fieldset style="width:300px; height:200px; overflow:scroll;">
<input type="checkbox" name="table[]" id="01" value='ado'> Adoption <br />
<input type="checkbox" name="table[]" id="02" value='acc'> Accomodations <br />
<input type="checkbox" name="table[]" id="03" value='ann'> Announcements <br />
<input type="checkbox" name="table[]" id="04" value="bea"> Beauty/Fitness <br />
<input type="checkbox" name="table[]" id="05" value="bus"> Business Oportunities
</fieldset>
and this one
<fieldset style="width:300px; height:200px; overflow:scroll;">
<input type="checkbox" name="State[]" id="01" value='AL'> Alabama <br />
<input type="checkbox" name="State[]" id="02" value='AK'> Alaska<br />
<input type="checkbox" name="State[]" id="03" value='AZ'> Arizona<br />
<input type="checkbox" name="State[]" id="04" value='AR'> Arkansas <br />
<input type="checkbox" name="State[]" id="05" value='CA'> California <br />
</fieldset>
Im using this code to go into their respective tables
$table = $_POST['table'];
$name = $_POST['name'];
$state = $_POST['State'];
if(is_array($table)){
while(list($tables) = each($table)){
$sql2 = "INSERT INTO tableName (name,table) VALUES ('$name','$tables')";
$q2 = mysqli_query($db_conx,$sql2);
}
}
if(is_array($state)){
while(list($key,$value) = each($state)){
$sql3 = "INSERT INTO states (name,State) VALUES ('$name','$value')";
$q3 = mysqli_query($db_conx,$sql3);
}
}
when it gets executed the only data that gets entered is states
I used
echo "table; ".$table."<br /> State; ".$state;
and got
table; Array
State; Array012ALAKAZ
someone help me!

You are vulnerable to sql injection attacks.
And your table query is using a reserved word, so the entire insert query is failing. Since you failed to check for failure, and simply assumed success, you'll never see any error messages.
Never EVER assume success when dealing with an external resource (especially a database). There's exactly ONE way for a query to succeed, and a near infinite number of ways for it to fail. Yet you seem to think that 1:infinity odds are really good.
$sql2 = "INSERT INTO tableName (name,`table`) VALUES ('$name','$tables')";
^-----^---you need these
$q2 = mysqli_query($db_conx,$sql2) or die(mysqli_error($db_conx));
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---you also need this

Here you have solution what makes only 2 queries instead of 20 and so queries:
$tables = $_POST['table'];
$name = $_POST['name'];
$states = $_POST['State'];
$states_values = '';
$tables_values = '';
$i = 0;
foreach($states as $state)
{
$i++;
$last = $i == count($states) ? true : false;
$states_values .= '(' . $name . ', ' . $state . ')' . ($last ? '' : ',');
}
$i = 0;
foreach($tables as $table)
{
$i++;
$last = $i == count($tables) ? true : false;
$tables_values .= '(' . $name . ', ' . $table . ')' . ($last ? '' : ',');
}
mysqli_query($db_conx, 'INSERT INTO states (name, State) VALUES ' . $states_values;
mysqli_query($db_conx, 'INSERT INTO tableName (name, table) VALUES ' . $tables_values;
As Marc said, you should escape your inputs.

Related

Inserting an array of checkbox values into a database including unchecked

In the form below, students are selected from student table in my DB. For each student selected a checkbox is checked if the student is absent and left unchecked if the student is present. The form is later on submitted for it to be inserted in the exam_status table in my DB.
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
while($row= $result->fetch_assoc())
{
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="matricule[]" value="<?php echo "$studentmatricule)"; ?>" readonly>
<label>Name</label>
<input type="text" name="name[]" value="<?php echo "{$studentname} {$studentsurname}"; ?>" readonly>
<label > Absent
<input type="checkbox" name="absent[]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
</form>
and my action page "action.php" is as follows
$matricule = $_POST['matricule'];
$absent=$_POST['absent'];
for ($i=0; $i<sizeof($matricule); $i++)
{
if($absent[$i]=='absent')
{
$status='absent';
}else{
$status='present';
}
$query = "INSERT INTO exam_status (student_matricule,status) VALUES ('". $matricule[$i] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
Now the issue is it doesn't just work as i want. the result always gives the first student absent and the rest present. I have tried all i can and have really researched too but with no success at all. Please anyone around to help me out?
Thanks in advance!
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
$index = 0;
while($row= $result->fetch_assoc())
{
$index++;
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][matriculate]" value="<?php echo $studentmatricule; ?>" readonly>
<label>Name</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][name]" value="<?php echo $studentname." ".$studentsurname; ?>" readonly>
<label > Absent
<input type="checkbox" name="studenInfo[<?php echo $index; ?>][status]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
Update your mail file like this. I have changed the form names into a single array. The reason is the checkbox values won't post to the page when the values are not checked. So its not possible to track which one was checked and which is not if you have same name.
And update your action.php like this,
<?php
$conn = mysqli_connect("localhost","username","password","db_name"); // update this values as per your configuration
$studenInfo = (!empty($_POST['studenInfo'])) ? $_POST['studenInfo'] : [];
foreach($studenInfo as $value ) {
$status = (isset($value['status'])) ? 'absent' : 'present';
$query = "INSERT INTO exam_status (student_name, student_matricule,status) VALUES ('". $value['name'] . "','". $value['matriculate'] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
?>
I have used my own table schema where i have added student_name in exam_status table for better tracking. Now you can see the values updating correctly. Also we can use bulk insert if we need to insert multiple data (Note : I haved used the bulk insert in this answer, i just followed the way you used)

Multiple checkbox search query fetching data from database in php

I have a multiple checkbox search query which fetches data from database. Below is the code:
HTML code:
<form action="search.php" method="post">
<input type="checkbox" name="cloth_color[]" value="Red" /> Red <br>
<input type="checkbox" name="cloth_color[]" value="Yellow" /> Yellow <br>
<input type="checkbox" name="cloth_color[]" value="Blue" /> Blue <br>
<input type="checkbox" name="cloth_color[]" value="Green" /> Green <br>
<input type="checkbox" name="cloth_color[]" value="Magenta" /> Magenta <br>
<input type="checkbox" name="cloth_color[]" value="Black" /> Black <br>
<input type="checkbox" name="cloth_color[]" value="White" /> White <br>
<input type="submit" value="SEARCH">
</form>
PHP code:
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1;
}
if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth = '$chk'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];
echo 'The cloth with ' . $colorofcloth . ' color';
echo '<br>';
}
}
?>
Now if I choose one option from the search select box I get query. But if I select two or more color I dont get the query. A help will be really appreciated.
P.S. I do have multiple joins in Mysql query but this is the place I am stuck so presenting as clear question as possible here. Also I intent to convert mysql to mysqli before the launch of this code. Thank you :)
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1 . ",";
}
if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth IN($chk)";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];
echo 'The cloth with ' . $colorofcloth . ' color';
echo '<br>';
}
?>
you can try this code which will use IN() of MySQL where you can pass multiple , separated values.
Hope this helps
Ok this is what i did. first of all got great help from #Dhaval and #Carlos as wasn't familiar with IN function in Mysql.
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= "'" . $chk1."', ";
//This is important as it is not the number it is a word so it should have a single quote if in query we are using double quote or vice versa.
}
$check_e = rtrim($chk,", ");
//Although i havn't checked in real time if mysql query will take last comma or not but it is a good practice to remove the last comma by rtrim.
if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth IN($check_e)";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];
echo 'The cloth with ' . $colorofcloth . ' color';
echo '<br>';
}
?>
What you may want to use is the Mysql IN CLause.
For this example, i am assuming that you use the correct syntax for the elements inside de IN Clause.
The correct syntax would be all the values that you need separated by commas, if you select red and blue.
$chk = 'red, blue'
Using the 'IN Clause' this query
$query = "SELECT * FROM clothings WHERE colorofcloth = '$chk'";
should transform to this.
$query = "SELECT * FROM clothings WHERE colorofcloth IN ('$chk')";
I do not know much about PHP, but for a database stand it should work.
Let me know if it works.

Notice: Undefined index: productID in .......product_list.php on line 14 [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I'm new to PHP and I've read many of the other undefined index error solutions on stackoverflow, but I still can't figure out why this rather simple code is receiving it. There's data in the database and everything else is pulling ok.
Right now I'm just trying to make sure the function and query are flowing through properly. So I purposely don't have if statements to check and see if the items are selected on the form because I'm always selecting them during testing. I must be missing something simple. Please help and thank you!
Form:
<!DOCTYPE html>
<html>
<head><title>Databases</title></head>
<body>
<h1>Music Store Database</h1>
<form method='POST' action='display.php'
<label>Select a table:</label>
<select name="tableName">
<option value="products">Products</option>
<option value="categories">Categories</option>
</select>
<p>Retrieve Record(s) - Select field(s) below:</p>
<input type="checkbox" name="productIDcb"/>
<label>ProductID</label><br />
<input type="checkbox" name="categoryIDcb"/>
<label>CategoryID</label><br />
<input type="checkbox" name="productCodecb"/>
<label>Product Code</label><br />
<input type="checkbox" name="productNamecb"/>
<label>Product Name</label><br />
<input type="checkbox" name="listPricecb"/>
<label>List Price</label><br />
<input type="checkbox" name="categoryNamecb"/>
<label>Category Name</label><br />
.
.
.
<p>Select the appropriate action based on your selection from above:</p>
<input type="radio" name="operation" value="retrieve"/>
<label>Retrieve Information</label><br />
<input type="radio" name="operation" value="addition"/>
<label>Add Information</label><br />
<input type="radio" name="operation" value="delete"/>
<label>Delete Information</label><br />
<p><input type="submit" value="Submit Request"/></p>
display.php File
<?php
require('database.php');
require('product_list.php');
$table = $_POST['tableName'];
$operation = $_POST['operation'];
$productIDcb = $_POST['productIDcb'];
$categoryIDcb = $_POST['categoryIDcb'];
$productCodecb = $_POST['productCodecb'];
$productNamecb = $_POST['productNamecb'];
$listPricecb = $_POST['listPricecb'];
if($operation == 'retrieve')
{
if($table == "products")
{
include_once('product_list.php');
show_products($table, $productIDcb, $categoryIDcb, $productCodecb, $productNamecb, $listPricecb);
}
}
?>
product_list.php file
<?php
include('database.php');
function show_products($table, $productIDcb, $categoryIDcb, $productCodecb, $productNamecb, $listPricecb)
{
global $db;
$theQuery = "select productId, categoryID, productCode, productName, listPrice ";
$theQuery .=" from ". $table;
echo($theQuery);
$rSet = $db -> query($theQuery);
$list = "";
foreach($rSet AS $products)
{
$list .= "".$products['productID']
. "".$products['categoryID']
. "".$products['productCode']
. "".$products['productName']
. "".$products['listPrice']
. "<br>";
}
echo($list);
}
?>
it is productId not productID in your select statement.
$products['productID'] should be $products['productId'] in product_list.php.
<?php
include('database.php');
function show_products($table, $productIDcb, $categoryIDcb, $productCodecb, $productNamecb, $listPricecb)
{
global $db;
$theQuery = "select productId, categoryID, productCode, productName, listPrice ";
$theQuery .=" from ". $table;
echo($theQuery);
$rSet = $db -> query($theQuery);
$list = "";
foreach($rSet AS $products)
{
$list .= "".$products['productId']
. "".$products['categoryID']
. "".$products['productCode']
. "".$products['productName']
. "".$products['listPrice']
. "<br>";
}
echo($list);
}
?>
productId and productID are considered different keys in php.

multiple arrays data posting and mysql insert using foreach php

i have form as below with same name text field columns, i want to insert multiple arrays data to mysql using this below form. pls tell me how to do this using foreach in php mysql
First Column
<input name="date[]" type="text" class="datepicker">
<input type="text" name="local[]" />
<input type="text" name="desc[]" />
<input type="text" name="ta[]" />
<input type="text" name="car[]" />
Second Column
<input name="date[]" type="text" class="datepicker">
<input type="text" name="local[]" />
<input type="text" name="desc[]" />
<input type="text" name="ta[]" />
<input type="text" name="car[]" />
First of all I would rename your form fields to make this easier:
<?php
$number_of_columns = 2;
for($i=0;$i<$number_of_columns;$i++) :?>
<input name="col[<?=$i?>][date]" type="text" class="datepicker">
<input type="text" name="col[<?=$i?>][local]" />
<input type="text" name="col[<?=$i?>][desc]" />
<input type="text" name="col[<?=$i?>][ta]" />
<input type="text" name="col[<?=$i?>][car]" />
<?php endfor;?>
And then once you get the data, you can just loop through the $_POST['col'] array and insert each one individually into the database. I'm assuming here that you've already connected to your database and are using the mysql library.
$cols = $_POST['col'];
$table = 'table_name';
foreach($cols as $col) {
$local = mysql_real_escape_string($col['local']);
$desc = mysql_real_escape_string($col['desc']);
$ta = mysql_real_escape_string($col['ta']);
$car = mysql_real_escape_string($col['car']);
mysql_query("INSERT INTO `{$table}` (`local`, `desc`, `ta`, `car`) VALUES('{$local}', '{$desc}', '{$ta}', '{$car}')") or die(mysql_error());
}
Try this code:
extract($_POST);
$n = count($date);
for ($i = 0; $i < n; $i++) {
$query = 'INSERT INTO `table` (`c1`, `c2`, `c3`, `c4`, `c5`) VALUES (\'' . $date[$i] . '\', \'' . $local[$i] . '\', \'' . $desc[$i] . '\', \'' . $ta[$i] . '\', \'' . $car[$i] . '\')';
// Here you must execute your query
}

php add multiple input fields to mysql

I have this code:
<html>
<body>
<form id="myForm" method="post" action="add-data.php">
<input type="submit">
<input type="text" name="pollquestion">
<input type="text" name="polloption1">
<input type="text" name="polloption2">
</form>
Add option
<script>
var optionNumber = 3;
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "polloption"+optionNumber+""; // poll[optionX]
newOption.type = "text";
theForm.appendChild(newOption);
optionNumber++;
}
</script>
</body>
</html>
If i add more inputs i will have something like this:
<input name="pollquestion" type="text">
<input name="polloption1" type="text">
<input name="polloption2" type="text">
<input name="polloption3" type="text">
<input name="polloption4" type="text">
<input name="polloption5" type="text">
<input name="polloption6" type="text">
The php code is something like this:
$qu = $_POST['pollquestion'];
$op1 = $_POST['polloption1'];
$op2 = $_POST['polloption2'];
$query = "INSERT into `".$db_table."` (question, option1, option2) VALUES ('" . $qu . "','" . $op1 . "','" . $op2 . "')";
How can i add this data to mysql for every added row? Thanks!
One way of many...
$query = "INSERT into `$db_table` SET `question` = '".mysql_real_escape_string($_POST['pollquestion'])."'";
foreach (range(1,6) as $idx) {
if (!empty($_POST['polloption'.$idx])) {
$query .= ", `option$idx` = '".mysql_real_escape_string($_POST['polloption'.$idx])."'";
}
}
of course the mysql_real_escape_string is important to avoid http://en.wikipedia.org/wiki/SQL_injection
First, you need to know how many options you're submitting so add another constant input to the form:
<input type="hidden" id="numOptions" name="numOptions"/>
In the addOption() function update its value (before incrementing optionNumber):
document.getElementById( "numOptions" ).value = optionNumber;
On the server side you need to create your query dynamically like so:
$options = array();
$values = array();
$numOptions = intval( $_POST[ "numOptions" ] );
for ( $i = 1; $i <= $numOptions; $i++ )
{
$options[] = "option$i";
$values [] = "'" . mysql_real_escape_string( $_POST[ "polloption$i" ] ) . "'";
}
$query = "INSERT INTO $db_table(" . implode( ',', $options ) . ") VALUES( '" .
implode( ',', $values );
Please mind the escaping of the received strings! very important to prevent SQL injections.
HTML
<input name="title" type="text">
<input name="descr" type="text">
<input name="question[1]" type="text">
<input name="option[1][1]" type="text">
<input name="option[1][2]" type="text">
<input name="option[1][3]" type="text">
<input name="right[1]" type="radio" value=1>
<input name="right[1]" type="radio" value=2>
<input name="right[1]" type="radio" value=3>
<input name="question[2]" type="text">
<input name="option[2][1]" type="text">
<input name="option[2][2]" type="text">
<input name="option[2][3]" type="text">
<input name="right[2]" type="radio" value=1>
<input name="right[2]" type="radio" value=2>
<input name="right[2]" type="radio" value=3>
PHP
$title = mysql_real_escape_string($_POST['title'])
$descr = mysql_real_escape_string($_POST['descr'])
$query = "INSERT into `polls` (title,descr) VALUES ('$title', '$descr')";
$id = $db->query($query);
foreach ($_POST['question'] as $num => $q) {
$q = mysql_real_escape_string($q)
$query = "INSERT into `poll questions` (poll,question) VALUES ($id,'$q')";
$db->query($query);
foreach ($_POST['option'][$num] as $i => $opt) {
$right = ($_POST['right'][$num]) == $i)?1:0;
$opt = mysql_real_escape_string($opt)
$num = intval($num);
$query = "INSERT into `poll options` (poll,num,option,right)
VALUES ($id,$num,'$opt',$right)";
}
}
You can iterate $_POST, matching keys with regular patterns, something like that:
foreach($_POST as $key => $value) {
preg_match('/(\w+)(\d+)/Uis', $key, $m);
if($m[1] == 'polloption') {
// concatenate new values to your query
}
}
Remembering relational databases, you have fixed number of attributes in your table. So you should add fixed number of options.

Categories