Insert multiple check box values into seperate columns in one row - php

I have displayed check box values(ugroup field) from group table.now what i want to do is,when user select multiple check boxes and submit it should be insert into relavent column in one row.now it's insert check boxes values.but not in relevant column .this is my code.Please help me.
//select ugroup's from group table.
<?php
$result = "SELECT id,ugroup FROM group";
$res_result = db::getInstance()->query($result);
?>
<form action="db_sql/db_add_page.php" method="get">
Tittle :<input type="text" size="100" name="tittle" />
Description :<textarea cols="80" id="editor1" name="description" rows="10"></textarea>
//Display ugroups in textboxes and checkboxes
<?php
while( $line=$res_result->fetch(PDO::FETCH_ASSOC)) {
echo '<input type="checkbox" name="group[]" value=" '. $line['ugroup'] .'" />';
echo'<input type="text" name="ugroup" disabled="disabled" value=" '. $line['ugroup'] .'" size="7" "/>';
echo ' ';
}
?><input type="submit" value="Submit">
</form>
db_add_page.php
if(isset($_POST))
{
$tittle = $_POST['tittle'];
$description = $_POST['description'];
$ugroup = $_POST['group'];
$acc_status = "INSERT INTO add_services (id,tittle,description,g1,g2,g3,g4,g5,g6,g7,g8)
VALUES(NULL,'".$tittle."','".$description."','".$ugroup[0]."','".$ugroup[1]."','".$ugroup[2]."','
".$ugroup[3]."','".$ugroup[4]."','".$ugroup[5]."','".$ugroup[6]."','".$ugroup[7]."')";
$rate = db::getInstance()->exec($acc_status);
if(!$rate){
echo '<script type="text/javascript">alert("Update Error !");</script>';
}else{
header('Location:../add_page.php');
echo '<script type="text/javascript">alert("Successfuly Updated User Group !");</script>';
}
}
i click on checkbox2,checkbox8 and submit.it's insert to g1 and g2.when i click on checkbox 1, checkbox3 its also added to g1 and g2.like below

Change line
echo '<input type="checkbox" name="group[]" value=" '. $line['ugroup'] .'" />';
To
echo '<input type="checkbox" name="group['.$line['id'].']" value=" '. $line['ugroup'] .'" />';
And yes start array index using 1

Normally, when we use $_POST values in checkboxes, those that are not checked will not be included in POST.
[group] => Array
(
[G1] => G1 // those the one you did not picked will not be included
[G3] => G3 // so that means your input is jagged
[G5] => G5 // you cannot hardcode each index (0 - 7)
[G7] => G7 // or they will be undefined (the ones that are missing)
)
So what you do is create a default value (an array) which will hold the defaults.
Then you combine those inputs, to the ones you have in default so that in return you will have a complete structure of insertion, instead of jagged inputs.
So in your form, do something like this:
while($line = $res_result->fetch(PDO::FETCH_ASSOC)) {
echo '<input type="checkbox" name="group['.$line['ugroup'].']" value=" '. $line['ugroup'] .'" />';
// assign G1, G2, indices
echo'<input type="text" name="ugroup" disabled="disabled" value=" '. $line['ugroup'] .'" size="7" "/>';
echo ' ';
}
Then on your processing form:
$default_values = array(); //create a default value
while($line = $res_result->fetch(PDO::FETCH_ASSOC)) {
$default_values[':' . $line['ugroup']] = '';
}
if(isset($_POST)) { // if submitted
$ugroup = array();
$temp = $_POST['group'];
foreach($temp as $val) {
$ugroup[':' . $val] = $val;
}
$combined_input = array_merge($default_values, $ugroup); // combine them so you have a complete structure
$sql = 'INSERT INTO add_services (tittle, description,g1,g2,g3,g4,g5,g6,g7,g8) VALUES (:title, :description, :G1, :G2, :G3, :G4, :G5, :G6, :G7, :G8)';
$acc_status = $db->prepare($sql);
$insert = array(':title' => $title, ':description' => $description,);
$insert = array_merge($insert, $combined_input);
$acc_status->execute($insert);
}

Related

Retrieve two GET parameters from a url and echo out in PHP

I have a form with multiple checkboxes and hidden inputs, which I'm passing to a second page using GET.
I'm then trying to retrieve the value of each checkbox and the input in a loop and echo out the combined value.
HTML:
<form action="criteria.php" method="GET">
<input name="id[]" type="hidden" value="<? echo $criteria_id; ?>" />
<input type="checkbox" name="checked[]" class="checkbox-md" id="<? echo $criteria_id; ?>" value="Y">
<button type="submit" class="btn btn-lilac" role="button">Complete</button>
</form>
PHP:
$criteria_id = $_GET['id']; //get all criteria id
$criteria_checked = $_GET['checked']; //get checked criteria id
foreach($criteria_id as $id) //get id of all checkboxes {
echo "<BR>Criteria = ".$id."Checked = ".$criteria_checked; //returns id + array?
if ($checked='Y')//check if checked {
echo "<BR>Criteria =".$id." Checked = Y";
} else {
echo "<BR>Criteria =".$id." Checked = N";
}
}
You will need to make sure that the inputs have matching array keys:
<input name="id[0]" type="hidden" . . .
<input name="checked[0]" type="checkbox" . . .
<input name="id[1]" type="hidden" . . .
<input name="checked[1]" type="checkbox" . . .
Depending on how you create these you could use the $criteria_id:
<input name="id[<? echo $criteria_id; ?>]" type="hidden" . . .
<input name="checked[<? echo $criteria_id; ?>]" type="checkbox" . . .
This way the id and checked array keys will match. All hidden inputs will be passed from the form but only the checked checkboxes, so check if the key of the id is set in the checked array:
foreach($_GET['id'] as $key => $id) {
if (isset($_GET['checked'][$key])) {
echo "<BR>Criteria =".$id." Checked = Y";
} else {
echo "<BR>Criteria =".$id." Checked = N";
}
}

php mysql: select from database and populate form

I would like to populate addresses for client from my db.
I use this code to select from db:
$stmt = $conn->prepare("SELECT * FROM peopleaddress WHERE peopleID=?");
if ( !$stmt ) {die(printf("Error: %s.\n", mysqli_stmt_error($stmt) ) );}
else if ( !$stmt->bind_param('i', $peopleID ) ) {die(printf("Error: %s.\n", mysqli_stmt_error($stmt) ) );}
else if ( !$stmt->execute() ) { die(printf("Error: %s.\n", mysqli_stmt_error($stmt) ) ); }
else {
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$addressID_array = array ($row['addressID']);
$addresstype_array = array ($row['addresstype']);
$addressactive_array = array ($row['active']);
$street_array = array ($row['street']);
$city_array = array ($row['city']);
$town_array = array ($row['town']);
$state_array = array ($row['state']);
$zip_array = array ($row['zip']);
$country_array = array ($row['country']);
$latitude_array = array ($row['latitude']);
$longitude_array = array ($row['longitude']);
}
} /* end else */
and this code to display the form:
<?php
for ($i = 0; $i < count($addressID_array); $i++) {
echo '<input type="text" name="street[]" id="" placeholder="street" value="';
if (isset ($street_array[$i])){echo $street_array[$i];} echo '" />';
echo '<input type="text" name="city[]" id="city" placeholder="city" value="';
if (isset ($city_array[$i])){echo $city_array[$i]; } echo '" />';
echo '<input type="text" name="zip[]" id="zip" placeholder="postalcode" value="';
if (isset ($zip_array[$i])){echo $zip_array[$i]; } echo '" />';
echo '<input type="text" name="town[]" id="town" placeholder="town" value="';
if (isset ($town_array[$i])){echo $town_array[$i]; } echo '" />';
echo '<input type="text" name="state[]" id="state" value="';
if (isset ($state_array[$i])){echo $state_array[$i];} echo '" />';
echo '<input type="text" name="country[]" id="country" value="';
if (isset ($country_array[$i])) {echo $country_array[$i];} echo '" />';
echo '<input type="text" name="addresstype[]" id="" value="';
if (isset ($addresstype_array[$i])) {echo $addresstype_array[$i];} echo '" />';
echo '<input type="text" name="addressactive[]" id="" value="';
if (isset ($addressactive_array[$i])) {echo $addressactive_array[$i];} echo '" />'; echo '<input type="text" name="latitude[]" id="latitude" READONLY value="';
if (isset ($latitude_array[$i])) {echo $latitude_array[$i];} echo '" />';
echo '<input type="text" name="longitude[]" id="longitude" READONLY value="';
if (isset ($longitude_array[$i])) {echo $longitude_array[$i];} echo '" /> <br>';
}
?>
Problems:
1) it only display one address, even if in db there are 2 addresses for the same client.
2) I'm pretty new at this. Am I doing it right or there is a fastest (less code) option to do this?
Thanks!!
The problem is within your while loop:
$addressID_array = array ($row['addressID']);
This assigns a new array every time the while loops to the variables. These assignment lines should all be changed like
$addressID_array[] = $row['addressID'];
As for your 2nd question: it is not really answerable because we do not know the requirements you need to work against.
Check out : https://en.wikipedia.org/wiki/SQL_injection
Look down at the "Hexadecimal Conversion" part. I put a short function to do SQL commands in there. When you get the information back it will be in an array. So if you used $row to get the information back it would be in $row[0][<Fields>], $row[1][<Fields>], and so on.
The problem with the above is - every time you do the "array()" it makes a new array. So it wipes what you had in there before. :-)
You are overwriting the values in your array by doing this
$addressID_array = array ($row['addressID']);
instead of
$addressID_array[] = $row['addressID'];
Update:
Also, it would be a good idea to iterate over your data, instead of making an array of data and then reading that array again. Use this:
else {
$result = $stmt->get_result();
}
// Then in display
while($row = $result->fetch_assoc()) {
echo '<input type="text" name="street[]" id="" placeholder="street" value="';
if (isset ($row['street'])){echo $row['street'];} echo '" />';
}

How to insert multiple check box values into table

I have displayed check box values(ugroup field) from ugroups table.now what i want to do is,when user select multiple check boxes and submit it should be insert into relavent feild in table.this is my code.it's doesn't work.please help me.
//select ugroup's from group table.
<?php
$result = "SELECT id,ugroup FROM group";
$res_result = db::getInstance()->query($result);
?>
group table
<form action="db_sql/db_add_page.php" method="get">
Tittle :<input type="text" size="100" name="tittle" />
Description :<textarea cols="80" id="editor1" name="description" rows="10"></textarea>
//Display ugroups in textboxes and checkboxes
<?php
while( $line=$res_result->fetch(PDO::FETCH_ASSOC)) {
echo '<input type="checkbox" name="ugroup" value=" '. $line['ugroup'] .'" />';
echo'<input type="text" name="ugroup" disabled="disabled" value=" '. $line['ugroup'] .'" size="7" "/>';
echo ' ';
}
?>
<input type="submit" value="Submit">
</form>
db_add_page.php
i want to add only selected check box values to relavant fields.
if(isset($_GET))
{
$tittle = $_GET['tittle'];
$description = $_GET['description'];
$ugroup = $_GET['ugroup'];
$acc_status = "INSERT INTO add_services (id,tittle,description,g1,g2,g3,g4,g5,g6,g7,g8) VALUES(NULL,'".$tittle."','".$description."','".$ugroup."','".$ugroup."','".$ugroup."','".$ugroup."','".$ugroup."','".$ugroup."','".$ugroup."','".$ugroup."')";
$rate = db::getInstance()->exec($acc_status);
if(!$rate){
echo '<script type="text/javascript">alert("Update Error !");</script>';
}else{
header('Location:../add_page.php');
echo '<script type="text/javascript">alert("Successfuly Updated User Group !");</script>';
}
}
add_services table
Store them in array than Run your query in while loop
Change this
echo '<input type="checkbox" name="ugroup" value=" '. $line['ugroup'] .'" />';
To this
echo '<input type="checkbox" name="ugroup[]" value=" '. $line['ugroup'] .'" />';
//See added [ ] afte ugroup
Than in another file you do this
$check_boxes = implode("','", $_POST['ugroup']);
$query="INSERT add_services (id,tittle,description,g1,g2,g3,g4,g5,g6,g7,g8)
VALUES (NULL,'".$tittle."','".$description."','{$check_boxes}')";

sql - update only changed values in form to multiple tables

This question is relevant with this question here
Lets say I have fetched values from multiple tables to a form, and want to change one or more inputs ie. phone number or address.
So here is my select query:
SELECT c.*, u.username
FROM client c
JOIN users u ON u.id = c.credid
WHERE credid = :id
Considering the linked question (and answer) above, how could I make prepared update query for values that have CHANGED?
My tables are InnoDB.
EDIT: I need to put username to users table and all else to clients table. (clients table field credid is foreign key to users table primary key id)
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<?php
echo 'Username: <input type="text" name="1" value="' . $getuserinfo['username'] . '" /><br>';
echo 'Client: <input type="text" name="2" value="' . $getuserinfo['company'] . '" /><br>';
echo 'Address: <input type="text" name="3" value="' . $getuserinfo['address1'] . '" /><br>';
echo 'Address 2: <input type="text" name="4" value="' . $getuserinfo['address2'] . '" /><br>';
echo 'ZIP: <input type="text" name="5" value="' . $getuserinfo['zip'] . '" /><br>';
echo 'City: <input type="text" name="6" value="' . $getuserinfo['city'] . '" /><br>';
echo 'Country: <input type="text" name="7" value="' . $getuserinfo['country'] . '" /><br>';
echo 'E-mail: <input type="text" name="8" value="' . $getuserinfo['email'] . '" /><br>';
echo 'Phone number: <input type="text" name="9" value="' . $getuserinfo['phone'] . '" /><br>';
?>
<input type="submit" name="submit" value="Save " /><br>
</form>
EDIT:
I would like to construct the sql somewhat like this.
UPDATE c.(name, address, zip, email, phone, etc.),u.username
VALUES (:1, :2, :3, :etc)
FROM client c
JOIN users u ON u.id = c.credid
WHERE credid = :id
Is this anywhere near?
Or maybe something like this:
UPDATE users,client
SET users.username = :username,
client.value1 = :value1,
client.value2 = :value2,
etc...
WHERE client.credid=users.id
What you'll need to do to start with is rename you inputs to the name of the table columns e.g.
foreach ($getuserinfo as $key => $val) {
echo ucfist($key).': <input type="text" name="'.$key.'" value="' . $val . '" /><br>';
}
The above won't give you the exact labels but it's easy enough to add an if statement in to change that.
After you initially get the information add it to the session array to check if anything has changed
$_SESSION = $getuserinfo;
Then after the form is posted back (remember this doesn't contain any validtion apart from checking if the index already exists in the $_SESSION)
if ($_POST['username'] != $_SESSION['user_edit_info']['username']) {
//run validation and query to update username
}
$posted = $_POST;
unset($posted['username']);
$sql_array = array();
$params = array();
foreach ($posted as $key => $val) {
//This should prevent extra fields being posted
if (isset($_SESSION['user_edit_info'][$key]) && $_SESSION['user_edit_info'][$key] != $val) {
$sql_array[] = "$key=:$key";
$params[$key] = $val;
}
}
if (!empty($sql_array)) {
$params['id'] = $_SESSION['user_id']; //or whatever you set it to in your session
//I don't know exactly how you're running your PDOs but below should at least show
//what you need to do
('UPDATE client SET '.implode(',', $sql_array).' WHERE credid=:id', $params);
}
//finally you don't need this anymore so just unset it
unset($_SESSION['user_edit_info']);
Hope this helps!

Insert group only if checkbox is checked

I am a little stuck with this. I am trying to insert groups of items only if that groups checkbox is clicked. I have tested the SQL insert without the checkboxes, and the SQL works perfectly and inserts the data. But when I added the checkboxes and if/else statement, it started to give me troubles.
For example:
-If I select group 1 and not group 2 - the SQL works correctly only inserting group 1 data
-If I select group 2 and not group 1 - The insert still inserts group 1 data
-If I select group 1 and group 2 - The SQL inserts two rows of group 1 data
-If I do not select any groups, then I get "Warning: Invalid argument supplied for foreach() in /home..." - which I will sort out later.
I have marked "Group 1" and "Group 2". I need the code to insert only the groups if checkbox is clicked, and ignore the non clicked checkbox groups. Any help would be great. Thanks.
I have been testing with the following code:
Form:
<form id="Form" method="post" action="/random.php" name="Form">
<input id="itemCurrency" type="hidden" value="2" name="itemCurrency"></input>
<div class="row">
<div class="col-lg-4">
<div class="itemHolder">
<img class="itemImg thumbnail" src="http://images.com/i/images.jpg"></img>
<div class="itemName">swim Shorts Wi...</div><
<div class="itemPrice">$33.33</div>
<div class="itemHref"><a target="_blank" href="http://random.com/product.aspx?id=40"> Visit Item Page </a></div>
</div>
</div>
//GROUP 1
<input id="itemCheckBox[]" type="checkbox" value="checked" name="itemCheckBox[]"></input>
<input id="itemName[]" type="hidden" value="some random text" name="itemName[]"></input>
<input id="itemHref[]" type="hidden" value="http://random.com/product.aspx?id=2140" name="itemHref[]"></input>
<input id="itemImg[]" type="hidden" value="http://images.com/i/image1s.jpg" name="itemImg[]"></input>
<input id="itemPrice[]" type="hidden" value="$37.33" name="itemPrice[]"></input>
//END GROUP 1
<div class="col-lg-4">
<div class="itemHolder">
<img class="itemImg thumbnail" src="http://images.com/i/image_xl.jpg"></img>
<div class="itemName">Bomber Jacket With Fur</div>
<div class="itemPrice"> $88.88</div>
<div class="itemHref"><a target="_blank" href="http://random.com/Bomber-Jacket-With-fur/..">Visit Item Page</a></div>
</div>
</div>
//GROUP 2
<input id="itemCheckBox[]" type="checkbox" value="checked" name="itemCheckBox[]"></input>
<input id="itemName[]" type="hidden" value="Bomber Jacket With Fur" name="itemName[]"></input>
<input id="itemHref[]" type="hidden" value="http://random.com/Bomber-Jacket-With-fur/.." name="itemHref[]"></input>
<input id="itemImg[]" type="hidden" value="http://images.com/i/image_xl.jpg" name="itemImg[]"></input>
<input id="itemPrice[]" type="hidden" value="$88.88" name="itemPrice[]"></input>
//END GROUP 2
<input id="site" type="hidden" value="1" name="site"></input>
<input id="submit_form" type="submit" value="yes" name="submit_form"></input>
</form>
PHP
if($submitForm == "yes" && $site == "1") {
foreach($_POST['itemCheckBox'] as $key => $val)
{
$fields[] = array(
'itemCheckBox'=>$_POST['itemCheckBox'] [$key],
'itemName' =>$_POST['itemName'] [$key],
'itemHref' =>$_POST['itemHref'] [$key],
'itemImg' =>$_POST['itemImg'] [$key],
'itemPrice' =>$_POST['itemPrice'][$key] );
//Remove non numaric characters from price(leave commas).
$itemPrice = preg_replace('/[^0-9,.]/s', '', $itemPrice);
//Data fields not in form
$userId = "username";
$userIp = $_SERVER['REMOTE_ADDR'];
$itemType = "ADD LATER";
$itemOutFit = "ADD LATER";
$site = "1";
$itemSale = "1";
//Only insert if checkbox is clicked --NOT WORKING, ????
if (isset($_POST['itemCheckBox'])){
echo "CHECKED";
echo "<br>";
/*** INSERT data ***/
$sql = "INSERT INTO items (userId,itemHref,itemImg,itemPrice,itemName,userIp,itemSite,itemType,itemCurrency,itemOutFit,itemSale) VALUES (:userId,:itemHref,:itemImg,:itemPrice,:itemName,:userIp,:itemSite,:itemType,:itemCurrency,:itemOutFit,:itemSale)";
$q = $conn->prepare($sql);
$q->execute(array(':userId'=>$userId,
':itemHref'=>$itemHref[$key],
':itemImg'=>$itemImg[$key],
':itemPrice'=>$itemPrice[$key],
':itemName'=>$itemName[$key],
':userIp'=>$userIp,
':itemSite'=>$itemSite,
':itemType'=>$itemType,
':itemCurrency'=>$itemCurrency,
':itemOutFit'=>$itemOutFit,
':itemSale'=>$itemSale));
} else {
echo "NOT CHECKED";
echo "<br>";
}
/*
echo $conn->errorCode();
echo "<br>"; ('SET CHARACTER SET utf8')
echo $conn->errorInfo();
echo "<br>";
//die(print_r($q->errorInfo(), true));
*/
}
UPDATE Tried to strip php down to basic code, still no luck. Does the same thing....anyone have an idea how I can fix this.
foreach($_POST['itemCheckBox'] as $key => $val)
{
$i = 0;
$itemCheckBox = $_POST['itemCheckBox'];
$itemName = $_POST['itemName'];
$itemHref = $_POST['itemHref'];
$itemImg = $_POST['itemImg'];
$itemPrice = $_POST['itemPrice'];
echo $i;
echo "<br>";
$i = $i +1;
if (isset($_POST['itemCheckBox'])){
echo "<br>";
echo "CHECKED";
echo "<br>";
echo "<br>";
echo $itemCheckBox[$i];
echo "<br>";
echo $itemName[$i];
echo "<br>";
echo $itemHref[$i];
echo "<br>";
echo $itemImg[$i];
echo "<br>";
echo $itemPrice[$i];
} else {
echo "NOT CHECKED";
echo "<br>";
$i = $i +1;
}
}
A couple things I spots that may be contributing to the issue:
In your PHP you have a line that has this:
//Remove non numaric characters from price(leave commas).
$itemPrice = preg_replace('/[^0-9,.]/s', '', $itemPrice);
I don't see where $itemPrice is defined though, should it be:
$itemPrice = preg_replace('/[^0-9,.]/s', '', $fields['itemPrice']);
Your issue of getting the "Warning: Invalid argument supplied for foreach() in /home..." can be solved by checking to make sure it exists and is an array beforelooping. You can use !empty() and is_array() to check.
if(!empty($_POST['itemCheckBox']) and is_array($_POST['itemCheckBox'])){}
Side Issue:
Your IDs for the inputs are all the same, "itemCheckBox[]", "itemName[]", etc.. are the same ID used for all of them. This may cause problems in the future if you want to use javascript or css properly.
Edit:
In your revised example the issue is that each time it cycles into the loop it is setting $i=0 because you declare it at the top of the foreach. If you go back to using the $key as the index it should work. See below:
//GROUP 1 checkbox
<input id="itemCheckBox[]" type="checkbox" value="0" name="itemCheckBox[]"></input>
//GROUP 2 checkbox
<input id="itemCheckBox[]" type="checkbox" value="1" name="itemCheckBox[]"></input>
I may also advise that you adjust your HTML items to match the Key you are passing:
<input id="itemName[1]" type="hidden" value="Bomber Jacket With Fur" name="itemName[]"></input>
<input id="itemHref[1]" type="hidden" value="http://random.com/Bomber-Jacket-With-fur/.." name="itemHref[]"></input>
<input id="itemImg[1]" type="hidden" value="http://images.com/i/image_xl.jpg" name="itemImg[]"></input>
<input id="itemPrice[1]" type="hidden" value="$88.88" name="itemPrice[]"></input>
foreach($_POST['itemCheckBox'] as $key => $val) {
$itemCheckBox = $_POST['itemCheckBox'];
$itemName = $_POST['itemName'];
$itemHref = $_POST['itemHref'];
$itemImg = $_POST['itemImg'];
$itemPrice = $_POST['itemPrice'];
if (isset($_POST['itemCheckBox'])){
echo "<br>";
echo "CHECKED";
echo $itemCheckBox[$key];
echo "<br>";
echo "<br>";
echo $itemCheckBox[$itemCheckBox[$key]];
echo "<br>";
echo $itemName[$itemCheckBox[$key]];
echo "<br>";
echo $itemHref[$itemCheckBox[$key]];
echo "<br>";
echo $itemImg[$itemCheckBox[$key]];
echo "<br>";
echo $itemPrice[$itemCheckBox[$key]];
} else {
echo "NOT CHECKED";
echo "<br>";
}
}

Categories