how to update multiple ids with different value - php

My form have multiple checkboxes in it (each with the code):
<input type="checkbox" name="id[]" value="<? echo $row['id'] ?>">
when user select id = 2 , 3 and 9 and submit the value. In my update php i am using following code to get selected value
echo "Check box test<pre>" ;
print_r($id);
echo "</pre>";
if(!empty($_POST['id'])) {
foreach($_POST['id'] as $check) {
echo $check."\n";
}
}
// update data in mysql database
$sql="UPDATE table SET display = '2' WHERE id IN ($check)";
i am always getting last selected id updated like 9
but i am not getting result as i wanted like
$sql="UPDATE table SET display = '2' WHERE id IN (2,3,9)";
. please Help what to do. i am very new to php.

You are doing nothing with $check, Make id like this
$ids="";
if(!empty($_POST['id'])) {
foreach($_POST['id'] as $id) {
$ids[] = $id;
}
}
$check = implode(",", $ids);

Because you are iterating the loop and $check will have latest value for the iteration.
foreach($_POST['id'] as $check) {
echo $check."\n";
}
Why can't you try instead ?
$check[] = $_POST['id'];

I think you need to get a better understanding of echo and the diference between server-side and client-side.
What you are looking for is implode
if(!empty($_POST['id'])){
$check = '(' . implode(',', $_POST['id']) . ')';
}

Related

How to Select Multiple Values from Database in php

How to solve
if i select one Value form dropdown. Biside I have another drop down and its values should be auto Updated According to Option I have selected from first dropdown ?
you can try to generate a lookup table whenever you create a drop-down list:
function createDropdown(&$ddlLookup) {
echo '<select multiple name="items[]">';
try {
$items = mysql_query("SELECT item_id,item_type FROM items");
while ($row = mysql_fetch_assoc($items)) {
echo '<option value="'.$row['item_type'].'"';
echo '>'. $row['item_type'] . '</option>'."\n";
$ddlLookup[$item_type] = $item_id;
}
}
catch(PDOException $e) {
echo 'No results';
}
echo '</select>';
}
Then whenever you need the id for a given description you use that table(array) to get it:
$mainDropdownLUT = array();
createDropdown($mainDropdownLUT);
var_dump($mainDropdownLUT['testCow']);
-> 734
Also, if you need to pass it to another page it can be serialized and added to a hidden field.
$mainDropdownLUT = serialize($mainDropdownLUT);
"<input type="hidden" value =\"$mainDropdownLUT\">"
-------------------------**OTHER PAGE **--------------
$mainDropdownLUT = unserialize($mainDropdownLUT);

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
}

How to use checkboxes to retrieve specific data in a database

Lately i have been working on a form with which a user can select a checkbox and as a result of the selection it shows the database information in a table.
I browsed the stackoverflow questions and found a question that was almost the same, namely: Retrieve data from sql database and display in tables - Display certain data according to checkboxes checked
So with this information, and some other information from the web, i started to create my code. Though after completion i had several errors, namely my database fields were duplicate on output, the data that the field had isn't outputted and there were two warnings. After a lot of searching and editing/trying i couldn't find the right solution so hence me asking this question in here.
Before i display my code i first give some information about the checkboxes, database and table/fields (and a (small) note: it is a wordpress database).
I have 1 database called xxx_wp1. THis database contains various (wordpress) table's but the table i want to retrieve information from is called: wp_participants_database.
This table contains various columns (around 15). Though, for this testing example i used just 3 of the 15 columns named: authorss, research_source and research_title. I inserted some random information (3 rows) in these 3 columns.
The form i created has, kinda obviously, 3 checkboxes for each column (so 1 for authors, research source and title).
Based on the previous link and some wordpress information i started to create my code for the selection, it is as follows:
<form method="post">
<input type="checkbox" name="columns[]" value="1" /><label for="Authors">Authors</label><br />
<input type="checkbox" name="columns[]" value="2" /><label for="Research Source">Research Source</label><br />
<input type="checkbox" name="columns[]" value="3" /><label for="Research Title">Research Title</label><br />
<input type="submit" name="go" value="Submit"/>
</form>
<?php
$all = false;
$column_names = array('1' => 'Authors', '2'=>'Research Source', '3'=>'Research Title');
$column_entries = isset($_POST['columns']) ? $_POST['columns'] : array();
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
if (empty($sql_columns)) {
$all = true;
$sql_columns[] = "*";
} else {
$sql_columns[] = "authorss,research_source,research_title,";
}
global $wpdb;
//DNI CHECKBOX + ALL
$tmp = $wpdb->get_results( "SELECT ".implode(",", $sql_columns)." FROM wp_participants_database");
$result = mysql_query($tmp);
echo "<table border='1' style='width:450px'>
<tr>
<th>authorss</th>
<th>research_source</th>
<th>research_title</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
while( $row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['authorss'] . "</td>";
echo "<td>" . $row['research_source'] . "</td>";
echo "<td>" . $row['research_title'] . "</td>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
echo '</table>';
?>
<?php
mysql_close();
?>
As you can see, the quesry is a bit different because it has to connect to the Wordpress database (the global $wpdb and $wpdb->get_results). While typing this im thinking that this might also be part of the problem as this get_results is already getting results which i am also getting later on?
Anyway, while testing this i get a few errors / misbehavior which i cant seem to figure out.
The first errors are the following warnings:
- Warning: mysql_query() expects parameter 1 to be string, array given in /home/xxx/domains/mysite.nl/public_html/Recap/wp-content/themes/radiate/templates/pdb-search-new.php on line 32 --- which is this line of code: `$result = mysql_query($tmp);`
- Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in /home/xxx/domains/mysite.nl/public_html/Recap/wp-content/themes/radiate/templates/pdb-search-new.php on line 43 --- which is this line of code: `while( $row = mysql_fetch_assoc($result))`
The second problem is that all of the columns are echo'd TWICE even before submitting. So this would mean this line of code is being done no matter what:
if (empty($sql_columns)) {
$all = true;
$sql_columns[] = "*";
} else {
$sql_columns[] = "authorss,research_source,research_title,";
}
When i check a option and press the submit button, the right column is being showed (so yay that works), though all the 3 columns are still being showed (no matter what) as well as the selected one, so i got this if i select the first option:
authorss research_source research_title Authors (notice the first 3 are from my defined while the last one is from my defined $column_names.
The last problem is that the field values of the columns isn't being showed, the columns are just empty.
So the question is of anybody could give me some pointers about what is going wrong.
Thank you in advance!
*****UPDATE*****
I made some adjusting with the help of #Zeusarm
So firstly i changed the warnings (among others the $wpdb->get_results is changed to $wpdb->query) and the warnings are all gone. For some reason i gave the $array_names just their front-end names (stupid me), so i changed it, like you suggested to the proper column names as they are in the database table. So field 1,2,3 became: authors, research_source and research_title.
I also added the other changes. Although the errors are all gone, i still get all 3 the columns showed + 1 duplicate (depending on the number of checkboxes selected). Plus i still don't get the database data which is stored in the columns (for example: authorss has the following stored values in it: Barry, Henk and Nicolas.).
The code now looks like (with the form left out as it remained the same):
<?php
$all = false;
$column_names = array('1' => 'authorss', '2' => 'research_source', '3' => 'research_title');
if(isset($_POST['columns'])){
$column_entries = $_POST['columns'];
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
$sql_columns[] = "authorss";
$sql_columns[] = "research_source";
$sql_columns[] = "research_title";
} else {
$all = true;
$sql_columns[] = "*";
}
global $wpdb;
//DNI CHECKBOX + ALL
$tmp = $wpdb->query( "SELECT ".implode(",", $sql_columns)." FROM wp_participants_database");
$result = mysql_query($tmp);
echo "<table border='1' style='width:450px'>
<tr>
<th>authorss</th>
<th>research_source</th>
<th>research_title</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
if($result!==false && mysql_num_rows($result)>0){
while( $row = mysql_fetch_assoc($result)){
echo "<tr>";
echo "<td>" . $row['authorss'] . "</td>";
echo "<td>" . $row['research_source'] . "</td>";
echo "<td>" . $row['research_title'] . "</td>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
echo '</table>';
}
?>
<?php
mysql_close();
?>
*****UPDATE 2*****
So i changed the code and finally i am retrieving the data of the database! So i guess i should just work with the wordpress get_results for querying from now on.
Although i am retrieving the information i still have duplicates. When i go to the page, at first i have all 3 duplicates and the data retrieving is being output in the first 3 columns. When i select 1 checkbox option, the correct data of that checkbox is being displayed and the other data from the other checkboxes isn't (so that works). Though, for example when i only choose the authors checkbox, the data of authors is being displayed in the first authors checkbox and only 1 duplicate (namely 'authors') is being showed. Though when i click only the second checkbox, research source (column research_source) then the data of that column is only being showed (what is correct) BUT that data is being output in thew first authors column and again, 1 duplicate with the correct column name namely 'research_source'.
But because a picture says more than a 1000 words, i added some images to clear it up. (sorry for the links to the pictures but missing 2 reputation to post pics directly)
The starting columns/page (untouched):
Only authors selected and submitted:
Left this one out as i can also only upload 2 links withh less than 10 rep...
Only Research Source selected and submitted:
I see at least 2 errors in your code.
the $column_names associative array values are supposed to be passed as field names, so I assume that they are not correct, as you have spaces in them (and as I know wordpress by default does not have such field names.
if some selection is provided by user you are adding some extra field names to the once which are passed by user and you have a colon after them so it will generate an error.
I would rewrite the code like this
<?php
$all = false;
$column_names = array('1' => '`field1`', '2' => '`field2`', '3' => '`field3`');
if(isset($_POST['columns'])){
$column_entries = $_POST['columns'];
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
$sql_columns[] = "authorss";
$sql_columns[] = "research_source";
$sql_columns[] = "research_title";
} else {
$all = true;
$sql_columns[] = "*";
}
Also as you have said $wpdb->get_results returns already the results - array so that's why you get the errors. Plus before calling mysql_fetch_assoc it is better to check if the passed parameter is recource and if the number of rows is not 0.
if($result!==false && mysql_num_rows($result)>0){
while( $row = mysql_fetch_assoc($result)){
...
}
}
*********** UPDATE ***********
according to last changes try this code:
<?php
$all = false;
$column_names = array('1' => '`authorss`', '2' => '`research_source`', '3' => '`research_title`');
if(isset($_POST['columns'])){
$column_entries = $_POST['columns'];
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
} else {
$all = true;
$sql_columns[] = "authorss";
$sql_columns[] = "research_source";
$sql_columns[] = "research_title";
}
global $wpdb;
//DNI CHECKBOX + ALL
$tmp = $wpdb->get_results( "SELECT ".implode(",", $sql_columns)." FROM wp_participants_database");
echo "<table border='1' style='width:450px'>
<tr>
<th>authorss</th>
<th>research_source</th>
<th>research_title</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
if(count($tmp)>0){
for($i=0;$i<count($tmp);$i++){
echo "<tr>";
foreach($tmp[$i] as $key=>$value){
echo "<td>" . $value . "</td>";
}
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
}
echo '</table>';
?>

Posting values to database

I am trying to post some values from checkboxes to my database, at the moment it does post a value, but only the last selected value (I currently have 8 checkboxes). Below is what I am using the get the checkboxes:
<?
$data = mysql_query("SELECT * FROM members WHERE active='Yes' ORDER BY name") or die(mysql_error());
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo "<input type='checkbox' name='attendees[]'";
echo 'value="' . $result['name'] . '">';
echo " ";
echo $result['name'];
echo "<br>";
}
?>
So they successfully show in my form and I can tick as many as I want however when I check the database, only the last one is showing.
I have been reading around and it seems like I need to store them in an array however this is the bit I am finding hard to understand.
Could anyone help me so that all values selected are shown in the DB and not just the last one?
EDIT: Too long to fit into a comment so here is the code where it adds the values to the DB
<?php
if(isset($_POST['submit']))
{
$date = $_POST['date'];
$score = $_POST['score'];
$attendees = $_POST['attendees'];
$result = mysql_query("INSERT INTO quiz_results (date, score, attendees)
VALUES ('$date','$score','$attendees')",$connect);
echo "<div class='alert alert-info'><b>Event Added!</b> - You'll will now be taken back to the previous page.</div>";
echo "<meta http-equiv=Refresh content=4;url=add-result.php>";
}//end of if($submit).
?>
$attendees = $_POST['attendees'];
$attendees is an array. You can't simply store the PHP array in the database without first transforming it into a string. You could store it as a comma separated list:
if ( is_array($attendees) ) {
$attendees = implode(', ', $attendees);
}
But, what happens when an "attendee" has a name that contains a comma? You could serialize it:
if ( is_array($attendees) ) {
$attendees = serialize($attendees);
}
But, in either case, what happens when you want to filter your data based on attendee? Now you have more problems.
The best way to manage this data (Google: database one-to-many relationships) is to store the attendees in a separate table that looks something like:
quiz_id attendee_id
1 20
1 42
1 50
See my answer at how to select from database based on a match in category? for an example.
Looks like you need to give each checkbox a different name.
$i=0;
while($result = mysql_fetch_array( $data ))
{
echo "<input type='checkbox' name='attendees[$i]'";
$i++
...
and I hope $_POST['attendees'] is an array?
Then when you insert into quiz results, you will need to loop through the arrays and insert one row of elements at a time into the database, you cant just insert arrays directly like that and expect each element to automatically take their own row.
Hope it helps, let me know.
View
<?php
$data = mysql_query("SELECT * FROM members WHERE active='Yes' ORDER BY name");
$html = '';
//And we display the results
while($result = mysql_fetch_array( $data )) {
$html .= sprintf( '<input type="checkbox" name="attendees[]" value="%d"> %s' , $result['id'] , $result['name'] );
}
echo $html;
When you post the form...
<?php
$attendees = isset( $_REQUEST['attendees'] ) ? $_REQUEST['attendees'] : null;
if( !is_null($attendees) && is_array($attendees)){
foreach( $attendees as $attendee){
// do something.. with attendee id
}
echo 'Ids: '.implode(', ', $attendees);
}

form with array of checkboxes send incomplete data

I try to pass a form which contains other forms (same inside forms, dynamic) , but I have checked that the data which are sent to the 'script handler' (php) are incomplete data. I think somewhere buffer is overwriting or something. Here is the code :
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
if($number== 0)
{
header('Location: /ceid_coffee/user_order_form.php');
}
else
{
$_SESSION['number'] = $number;
echo '<form action="user_order_form.php" method="POST">';
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<br>';
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
}
echo '<br>';
}
echo '<input type="submit" name="submit" value="FINAL_ORDER">';
echo '</form>';
}
}
?>
And this is the handling script:
<?php
if (isset($_POST['submit']))
{
$number= $_SESSION['number'];
$item = $_SESSION['item'];
$max_id = "SELECT MAX(id_order) FROM id_of_orders";
$x=mysql_query($max_id) or die("my eroors");
$id= mysql_fetch_array($x);
$xyz = $id['MAX(id_order)'];
for($i=0;$i<$number;$i++)
{
$temp = $_POST['yliko'][$i]; // <~~~~ this line is the form's data
$temp2 = implode("," , $temp);
$inserts = ("INSERT INTO orders (order_id,product,ulika) VALUES ('$xyz' , '$item','$temp2')");
$inc_prod=("UPDATE proion SET Counter = Counter + 1 WHERE proion.onomasia='$item'");
mysql_query($inserts) or die(mysql_error());
mysql_query($inc_prod) or die(mysql_error());
}
}
?>
This line here contains the data of each form , but i have echo them ($temp2) and i saw that they are incomplete.
$temp = $_POST['yliko'][$i];
If i select more than 1 checkbox for each item ($i) I get only one value from the checkboxes into the sql.
Do you see if I miss something ?
Ok i found the error. I replace this row :
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
with this row :
echo '<input type="checkbox" name="yliko['.$i.'][]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
I do not know how (i'm new to php) but it worked.
You will only get one value for each form because you are assigning the value of $i to each one:
echo '<input type="checkbox" name="yliko[][$i]" value='. etc.
is your problem line.
Have a look at the HTML that your code produces (ctrl-u in most browsers) and you will see why you get the wrong answer. All your checkboxes need to have unique names.
I would do it by assigning each checkbox a name that relates to the line in the database from which they are drawn eg:
name="checkbox_"'.$row['ylikaprimarykey']."etc.
This will get you up and running fairly quickly. For what it is worth, the ids of your table keys can give attackers information about your site so it is best practice to obfuscate them in some way. There are a number of excellent classes available free on the net that will do this for you.
If you really need to deal with what would have been in each form as a separate chunk of data, you can easily change the checkbox names vis:
name="checkbox_$formnumber_$obfuscatedkeynumber"
then loop through them with nested loops in your handling page.

Categories