PHP Select List - Insert multiple values in database - php

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}'");
}

Related

PHP- is unable to read the other checked checkbox

I stored the data in a supposed to be an array but what happens is that only the last checked checkbox is the only one that is registered in the idSkills. This is the part of the code wherein the skills are displayed through a query in the database
<?php
$i=0;
while ($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$skillName=$row['skillName'];
?>
<input type="checkbox" name="skills[]" value="<?php echo $id; ?>"><?php echo $skillName; ?><br>
<?php
$i++;
}
?>
Here is the part where the loop unveil all of the selected checkbox
//QUERY TO INSERT
$conn = new mysqli($config['servername'], $config['username'], $config['password'], $config['database']);
$idSkills = $_GET['skills'];
if(empty($idSkills))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($idSkills);
echo("You selected $N door(s): ");
echo("$idSkills[1] ");
for($i=0; $i < $N; $i++) {
echo "Skill ID: "
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('$idSkills[$i]','$idVolunteer')";
$result = $conn->query($sql);
}
}
$conn->close();
It would be best to use a prepared statement instead of substituting a variable into the SQL. But if you're going to do it this way, you need to use the correct syntax:
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('{$idSkills[$i]}','$idVolunteer')";
You need to put {} around an array reference in order to get the variable inside the brackets to be evaluated. See the section on Complex (curly) Syntax in the PHP Strings documentation.

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: get option select value by mysql

I'm trying to have an altas.php file for various html forms. This code is a html form with some mysql columns:
<div><label for="categoria">Categoría principal</label><select type="text" name="categoria">
<?php
$query = "select id, categoria from categorias";
$result = mysqli_query($mysql,$query);
if(!$result) echo 'Muy mal....';
$num_filas = mysqli_num_rows($result);
for ($i = 0; $i < $num_filas; $i++){
$row = mysqli_fetch_array($result);
?>
<option value "<?php echo $row['id']?>"><?php echo $row['categoria']?></option><?php
}
?>
</select></div>
On the other hand, if I make this:
foreach($_POST as $campo => $valor){
echo $campo ." = ". $valor ."\n";
}
I have no data in $row['categoria']. It should return the value, which is the categorias's id.
Another question:
How can I use the "foreach" whith an insert sentence?
For example:
foreach($_POST as $campo => $valor){
$query ="INSERT INTO $tabla ($campo) VALUES ('$valor')";
}
$tabla is sent via $_GET. This code make a new row for each $campo. Any idea?
I have try some suggestions, but nothing works.
You seem to be missing an = and closing semi-colons on this line:
<option value "<?php echo $row['id']?>"><?php echo $row['categoria']?></option><?php
Should be:
<option value="<?php echo $row['id']; ?>"><?php echo $row['categoria']; ?></option><?php
EDIT:
Also removed type from select list

white spaces in $_POST

I have a HTML dropdown list populated by PHP as following:
<form name="selectOccupation" method="post" action="specific_occupation.php">
<div align="centre">
<select name="occupation_dropdown" id="occupation_dropdown">
<?php
include "connection.php";
$sql = mysql_query("SELECT DISTINCT Occupation from patient_info");
while ($row = mysql_fetch_array($sql)) {
echo "<option value=".$row['Occupation'].">".$row['Occupation']."</option>";
}
?>
</select>
</div>
<br>
<br>
<input type="submit" name="submit" value="Proceed"/>
</form>
In the specific_occupation.php file, I have this code:
<?php
include "connection.php";
$selectedoccupation = $_POST['occupation_dropdown'];
echo $selectedoccupation;
$myquery = "SELECT patient_info.Name, test_info.DateOfTest FROM `patient_info`,`test_info` WHERE patient_info.PatientID = test_info.PatientID AND patient_info.Occupation = '$selectedoccupation' ";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
$tempdata = json_encode($data);
?>
This works fine if an occupation without any white space between them like "carpenter" is selected from the dropdown menu but doesn't work for "sales person". How can the $_POST be used for occupations with white spaces??
Thanks in advance !!
You're building your HTML wrong. You've got it as:
<option value=Sales Person>
^^^^^---what will get sent as the value
^^^^^^---some wonky unknown/non-standard attribute
This is incorrect. HTML now requires that ALL attributes be quoted:
<option value="Sales Person">
and even when the quotes weren't required, you still had to have the quotes to handle "spaced" data like this.
PHP post replace some characters such as - with whitespaces.
You can try urlencode($var) in your PHP script.

Not getting array values when posting them in a form

I have gone through various posts but can't find a solution to this problem:
I have a form with several rows of fields to insert in a database table with one Click of the submit button. This is the code of the HTML:
<form action="filename.php?cartID=<?php echo $_GET['cartID'];?>&customer_id=<?php echo $_GET['customer_id'];?>&total_count=<?php echo $_GET['total_count'];?>&action=add" method="post" id="add_participants" >
<table>
<?php for ($i=0, $n=$_GET['total_count']; $i<$n; $i++) { ?>
<input type="hidden" name="customer_id[]" id="customer_id[]" value="<?php echo $_GET['customer_id'];?>" />
<input type="hidden" name="cartID[]" id="cartID[]" value="<?php echo $_GET['cartID'];?>" />
<input type="hidden" name="products_id[]" id="products_id[]" value="<?php echo $_GET['products_id'];?>" />
<tr><td><label for="title[]">Title</label></td><td><select id="title[]" name="title[]">
<option value="Dr">Dr</option>
<option value="Miss">Miss</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Prof">Prof</option>
</select>
</td>
<td><label for="firstname[]">First Name</label></td><td><input type="text" id="firstname[]" name="firstname[]"/></td>
<td><label for="surname[]">Surname</label></td><td><input type="text" id="surnam[]e" name="surname[]"/></td>
<td><label for="email[]">E-mail</label></td><td><input type="text" id="email[]" name="email[]"/></td></tr>
</table>
<?php } ?>
<input value="Add participant" type="submit" />
On the action page the code is the following:
for ($i=0, $n=$_GET['total_count']; $i<$n; $i++) {
$title[$i] = tep_db_prepare_input($HTTP_POST_VARS['title.$i]']);
$firstname =tep_db_prepare_input($HTTP_POST_VARS['firstname.$i']);
$surname =tep_db_prepare_input($HTTP_POST_VARS['surname.$i']);
$email = tep_db_prepare_input($HTTP_POST_VARS['email.$i']);
$customer_id = tep_db_prepare_input($HTTP_POST_VARS['customer_id.$i']);
$cart_id = tep_db_prepare_input($HTTP_POST_VARS['cartID.$i']);
$products_id = tep_db_prepare_input($HTTP_POST_VARS['products_id.$i']);
$query = "INSERT INTO participants (title,Firstname,Surname,Email,customers_id,cart_id,products_id) VALUES ('$title[$i]', '$firstname[$i]', '$surname[$i]', '$email[$i]', $customers_id[$i], $cart_id[$i], $products[$i])";
echo $query . "<br />";
mysql_query($query) or die(mysql_error());
}
However, I cannot get the values of the $_POST variables into the variable arrays to use in the insert statement.
Can anyone help me with this please? I have tried different permutations of the code, and I'm still not getting anywhere.
Many thanks.
I'm fairly certain that $HTTP_POST_VARS is deprecated.. you should be using $_POST instead.
Secondly, your processing doesn't really need to loop over a for loop. You could use foreach to loop over all posted values instead.
Example (untested):
foreach($_POST['customer_id'] as $key => $customerID) {
$title = !empty($_POST['title'][$key]) ? $_POST['title'][$key] : "";
$firstName = !empty($_POST['firstname'][$key]) ? $_POST['firstname'][$key] : "";
// etc...
}
if your keeping the loop the same way, you need to make a change to how you refer to your array elements. change $title[$i] = tep_db_prepare_input($HTTP_POST_VARS['title.$i]']); to
$title[$i] = tep_db_prepare_input($_POST['title'][$i]);
and change the rest of your assignments to follow the same pattern.
The output of tep_db_prepare_input() is of course a mistery, but apart from that it's true what Marc B. says: "Learn basic PHP syntax rules"
$query = "INSERT INTO participants (title,Firstname,Surname,Email,customers_id,cart_id,products_id) VALUES ('$title[$i]', '$firstname[$i]', '$surname[$i]', '$email[$i]', $customers_id[$i], $cart_id[$i], $products[$i])";
echo $query . "";
This will output exactly what's between the double quotes. Try using:
$query = "INSERT INTO participants (title,Firstname,Surname,Email,customers_id,cart_id,products_id) VALUES ('".$title[$i]."', '".$firstname[$i]."', '".$surname[$i]."', '".$email[$i]."', ".$customers_id[$i].", ".$cart_id[$i].", ".$products[$i].")";
echo $query . "";
Using "{$array[$key]}" within double quotes also works, but using "$array[$key]" within double quotes does not work.
Further, $HTTP_POST_VARS is deprecated. Use $_POST
Your code has multiple errors that result in unintended values:
$title[$i] = tep_db_prepare_input($HTTP_POST_VARS['title.$i]'])
foreach is definitely clearer than a for loop
What others said: $HTTP_POST_VARS must be $_POST (or $_REQUEST)
Assuming that your mysterious tep_db_prepare_input() functions correctly, $HTTP_POST_VARS['title.$i]'] is syntactically incorrect. Single quotes mean variables are not parsed: your function is passed the (invalid) contents of $_POST['title.$i]']. I believe you meant to write $POST["title$i"] (where the "." is part of the field name. (Personally an underscore would be less confusing as "." has meaning in PHP.)
So... fix all that and you should be good to go. Well, #2 & 3, at least.

Categories