I was looking in stackoverflow, but i do not find exactly what I need. I need to insert checkboxes data sent with php into mysql like this 22111,22332,12123,121132.
I have this code (found here in the site)
<?php
foreach($_POST['idecod'] as $check) {
$sel = $check.',';}
$contenedor = "UPDATE inmdes SET idecod='$sel'";
$insertdb = mysql_query($contenedor) or die(mysql_error());
?>
Of course I have the checkboxes as an array:
<input name="idecod[]" type="checkbox" value="<?php echo $rs[0]; ?>" />
How can i insert multiple checkboxes like 2211223,2211223,1212233,12332122 or if is just one 222111222..???
And how can i retrive them as an array because i need to use something like this
<? php if (in_array('2211223', $idecod)) echo "checked"; ?>
To automatically check the previous checked boxes.!
Thanks in advance
Roberto
UPDATE
I have a list of options. These options act/des with checkboxes. I need to:
1.- Be able to register options checked (SOLVED thanks to #prodigitalso)
2.- Be able to automatically check the checkboxes previously checked.
So, I have the codes like this 221122,221133,225566,445522 in the table (mysql). I need the script to check what codes where previously checked (those that are in the table) and check them. For example:
I see the 5 options 221122,221133,225566,445522 and 663322. I check only 4 (221122,221133,225566,445522) and this is UPDATED in mysql database.
I come again to the options page. But previously i checked 221122,221133,225566,445522. So the script check EACH checkbox. So automatically check options 221122,221133,225566,445522 BUT it doesnt check 663322.
RS[0] is the code, for example 221122.
You can use implode and explode function to do this
$string = implode(",", $array);
$array = explode(",", $string);
You should use explode and implode.
if(isset($_POST['idecod']) && !empty($_POST['idecod'])) {
$sel = implode(',', $_POST['idecod']);
$contenedor = sprintf("UPDATE inmdes SET idecod='%s'", mysql_real_escape_string($sel));
$insertdb = mysql_query($contenedor) or die(mysql_error());
}
then when you pull them out just use:
$idecodArr = explode(',', $row['idecod']);
Related
Mission: Verify that "players" have placed vintage promotional jpegs on their social media site(s). Doing so earns them crypto tokens towards game play. All non-verified postings are displayed on an administrator's dashboard with a checkbox if the listing has been visually verified and "Approved." The value of each checkbox is the database ID of the listing (see screen capture). Once the listings have been verified and the check box ticked, the page is POST(ed) to a query page where the default value "confirm" is changed from 0 to 1. This then awards them the designated tokens.
enter image description here
However, I haven't found the right formula of code to get the UDPATE to work. The checkbox values will display in "echo" mode, but the SQL won't function within the FOREACH loop.
<?php
$checked_arr = $_POST['checkbox'];
$count = count($checked_arr);
echo "There are ".$count." checkboxe(s) are checked <br>";
foreach($_POST['checkbox'] as $val) {
$sql = "UPDATE media SET confirm = 1 WHERE id = $val " ;
echo "$val\n";
?>
Scoured the Net for working examples, including Stack Overflow, but to no avail. Assume there's a simple answer here, but as a novice PHP programmer, it eludes me.
Thank you in advance for suggestions.
you could use the IN operation in the conditional.
The only thing you would have to do is capture all the IDS and do an "implode" to give it the format that is needed for the sql.
for example:
<?php
$ids = [];
foreach($_POST['checkbox'] as $val){
$ids[] = $val;
}
$values = implode(",", $ids); // => 'id1, id2, id3, ...'
// this is a massive update based on selected items
$sql = "UPDATE media SET confirm = 1 WHERE id IN ($values)";
?>
i have created one table called role and the fields are like (roleid,role,prohibitedprocess,prohibitedports) here roleid is unique. and i have a comma separated value for "prohibitedprocess" field .(ex: prohibitedprocess---> skype,teamviwer,notepad).
the problem is how to add and edit and delete that comma separated value of prohibitedprocess .is it possible ?
i have fetch the code form the data base .code is
<?php
$sql = "SELECT roleid, prohibitedprocess, prohibitedports FROM role WHERE role='Basic'";
$option='';
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
$pro_proc = $row['prohibitedprocess'];
$lst = explode(",",$pro_proc);
//Print in Option Box
foreach($lst as $exp)
{?>
<tr>
<td><?php echo $exp;?></td>
<td>Edit</td>
<td>Delete</td></tr>
<?php
}
}
?>
How to do this please help me
You can edit the whole string . .
I mean just using str_replace function
e.g
$string = "skype,teamviwer,notepad";
$old_value = "skype";
$new_value = "facebook";
$new_string = str_replace($old_value,$new_value,$string);
Then simply update this new string into database table. .
One way would be to retrieve all of 'keywords' in an input element and edit them like a sentence. However, for what you want to do, you may wanna add a new table called prohibitedprocess and use roleid as a foreign key. Then retrieve from that table according the roleid.
eg: SELECT item FROM prohibitedprocess p, role r WHERE p.roleid = r.roleid
It may be better to make another table for that relation, then you could edit it normally. Otherwise you can take your comma separated list and do something in javascript.
var commaSeparatedList = <?php echo $commaSeparatedList;?>
var realData = commaSeparatedList.split(',');
// when the user adds something you can add to the array or delete
// from the array
var newCommaList = readData.join([separator = ',']);
// some kind of get/post request that sends the new comma list
<?php
$newList = GET_REQUEST_PARAMS["newCommaList"];
// sql update query that updates the comma list
?>
I haven't used php in a while so I know GET_REQUEST_PARAMS isn't a thing but i'm sure you know how to get the parameters.
Or without javascript you can use a form that posts back all the names of prohibited things
<?php
$newList = ""
//foreach through the get params which contain the names
foreach()
{
$newList += getParam + ",";
}
// some code to remove that last comma
// sql update
?>
I have this update statement (PHP code):
$sql1="UPDATE `utilizatori` " .
"SET utilizator='$utilizator', parola='$parola1', nume='$nume', " .
"`prenume='$prenume', varsta='$varsta', localitate='$localitate'` ";
WHERE parola='".$_SESSION['parola']."'";
This will update some MySQL table fields via an html form. The user wants to change just his name for instance. He completes just name field, then he presses submit. The data is sent into the table with the UPDATE statement above.
The problem is that it also updates the table with blank values that user didn't complete. I don't want the blank values to be added.
How can I block the blank values to be sent into the table?
If you really wanted to do this in the update, you can change the set statement to something like:
set utilizator = (case when '$utilizator' <> '' then '$utilizator' else utilizator end),
. . .
This will use the previous value if the new one is blank.
You can also do this at the application level by just updating the fields that have changed.
And, you should use parameterized queries rather than directly substituting values into a string. That is another issue, though.
You can do two things to solve this issue. One is to preload the data in the form. So when the user change his name, the other fields are already loaded with the original information.
The second option is to create an update query based on the fields have a value.
Example of option 1:
<?php
//
//GET THE DATA FROM A SELECT QUERY HERE
//FOR EXAMPLE: $sql = "SELECT * FROM `utilizatori` WHERE parola='".$_SESSION['parola']."'";
//Put the data of the sql row in a variable e.g. $sqlRow.
?>
<!--Use variable in your form!-->
<form>
...
...
<input name="nume" value="<?=$sqlRow['nume']?>"/>
<input name="utilizator" value="<?=$sqlRow['utilizator']?>"/>
...
...
</form>
Example of option 2:
<?php
//Catch post data
if($_POST)
{
$updateString = "";
foreach($_POST as $inputField => $inputValue)
{
if($inputValue != "")
{
$updateString .= $inputField." = '".$utilizator."',";
}
}
//Strip last ,
$updateString = substr($updateString,0,-1);
if($updateString != "")
{
//Your query would be
$sql1 = "UPDATE `utilizatori` SET ".$updateString." WHERE parola='".$_SESSION['parola']."'";
}
}
?>
$updateClauseArr = Array();
foreach($_REQUEST as $key => $val){
if(is_numeric($val)){
$updateClauseArr[] = '$key = '.(int) $val;
}else{
$updateClauseArr[] = "$key = '".htmlentities($val,ENT_QUOTES,'UTF-8')."'";
}
}
if(sizeof($updateClauseArr) > 0){
$updateSet = implode(',' ,$updateClauseArr);
$sql1="UPDATE `utilizatori` SET ".$updateSet." WHERE parola='".$_SESSION['parola']."'";
}
See what field values have been submitted by the user. then iterate in a loop for the fields that have value to make variable to be concatenated to the update query.
Here is my PHP variable:
$container = $_POST['containerNumber'];
Inside $_POST['containerNumber'], there are multiple container numbers that are retrieved when a user checks a checkbox from a form. That code is not necessary to display. Just know that $_POST['containerNumber'] can have multiple container numbers assigned to it.
What I need to do is extract each container number from the POST so that I can run a mysql INSERT statement per each container number.
In the database table, there are multiple columns, with container_num being the column I'm trying to update (for now).
How can I turn $container into an array and retrieve each container number that has been assigned to the variable?
I know I need to utilize a FOREACH loop. With that said, there will more than likely be multiple INSERT statements that will automatically be created with the loop.
$SQL = "INSERT INTO myTable (container_num) VALUES ('$container')";
// times however many containers the variable $container had stored in it
Please help.
EDIT **
Once the user checks however many checkboxes, I can display each container like this:
<INPUT name="containerNumber" id="containerNumber" class="containerNumber" />
When I do this, it can be displayed to the screen like this:
CONT_ID001, CONT_ID002, CONT_ID003...
I hope this helps.
There are multiple ways of doing this.
1) Give the POST parameters you're sending a name that ends with [], PHP automatically assigns them to an array when parsing the POST data. If you're sending the data from an HTML form, this is an example of how to do it:
<form action="" method="POST">
<label>
First container number:
<input type="text" name="containerNumber[]" />
</label>
<label>
Second container number:
<input type="text" name="containerNumber[]" />
</label>
<input type="submit" />
In PHP you can just do
foreach($_POST["containerNumber"] as $container) {
...
}
(Note that this is a feature of PHP and not portable to other server-side langages. This is NOT part of the HTTP specification.)
2) Separate values using some separator, in PHP use explode() to split it.
3) Send the form as JSON or encode that one field as JSON (if sent from HTML, I suggest using jQUery to do either option, as it's the easiest way) and use json_decode() in PHP to extract the contents.
4) Sevaral other options that may be suitable, depending on what exactly you're doing.
If I get you, you have a $_POST variable with multiple values.
If the content of $_POST['containerNumber'] is CONT_ID001, CONT_ID002, CONT_ID003
You can do this:
$result = preg_split("/, /", $_POST['containerNumber']);
//the result dump will be:
//$result[0] = "CONT_ID001";
//$result[1] = "CONT_ID002";
//$result[2] = "CONT_ID003";
The insert code should looks like to (assuming that you have one column for each number):
$SQL = "INSERT INTO myTable ";
$columns = "";
$values = "";
foreach (result as $id=>$out){
$columns .= "container_$id";
$values .= "'$out'";
if (count($result) < $id+1){
$columns .= ", ";
$values .= ", ";
}
}
$SQL .= "($columns) VALUES ($values)";
If you only have container_num column it should looks like:
$SQL = "INSERT INTO myTable (container_num) VALUES ('";
$columns = "";
$values = "";
foreach (result as $id=>$out){
$values .= $out;
if (count($result) < $id+1){
$values .= ", ";
}
}
$SQL .= "$values')";
I'm making a simple online store like program. What can you suggest that I would do so that I can loop through the inputs I've made in my program.
I'm still using get so that I could see how the data looks like, I'll change it to post later.
This is what the url looks like, when I commit the buying of all the products added in the cart:
http://localhost/pos/php/checkout.php?ids=2;&qoh=12;&qbuys=&ids=6;&qoh=2304;&qbuys=304&ids=4;&qoh=699;&qbuys=99
This is the code that I'm using to commit only one product, it doesn't work when I had something like in the above url:
<?php
$id=$_GET['ids'];
$qtyhnd=$_GET['qoh'];
$qtytbuy=$_GET['qbuys'];
$left=$qtyhnd-$qtytbuy;
if($qtyhnd>=$qtytbuy){
$update=query_database("UPDATE prod_table SET QTYHAND='$left' WHERE PID='$id'", "onstor", $link);
}
?>
Please comment if you need more details,thanks
Either convert the parameters to array parameters (e.g. qoh[]) and then iterate in parallel, or parse the query string manually.
You have semicolons after some values maybe you should pass just the integer this are qoh and qbuys.
Apart of that you should use mysql_real_escape_string() and (int) before integer values to prevent SQL injection e.g.:
$int = (int)$_GET['price'];
$string = $_GET['val'];
mysql_real_escape_string($string);
Also if you want to pass multiple values you have to use array for them:
HTML
<input type="hidden" name="ids[]" value="1">
<input type="hidden" name="ids[]" value="2">
<input type="hidden" name="ids[]" value="3">
PHP
$ids = $_GET['ids'];
foreach($ids as $id) {
$sql = 'UPDATE table SET field=? WHERE id='.(int)$id;
....
}
You can use the $_SERVER['QUERY_STRING'] with foreach loop like this:
foreach($_SERVER['QUERY_STRING'] as $key => $value){
echo "$key - $value <br />";
}
This way you can get the values of GET and use in your database query in similar fashion using foreach loop.
I assume that PID in prod_table is of integer type. Doesn't $id variable contain "2;" instead of 2? Anyway, what kind of error do you get?
Have your url like
http://localhost/pos/php/checkout.php?ids[]=2&qoh[]=12&qbuys[]=&ids[]=6&qoh[]=2304&qbuys[]=304&ids[]=4&qoh[]=699&qbuys[]=99... using a HTML structure like infinity pointed out.
Then:
foreach ($_GET['ids'] as $k => $v) {
$id = (int)$v;
$qtyhnd = (int)$_GET['qoh'][$k];
$qtytbuy = (int)$_GET['qbuys'][$k];
$left = $qtyhnd - $qtytbuy;
if ($qtyhnd >= $qtytbuy) {
$update = query_database(
"UPDATE prod_table SET QTYHAND='$left' WHERE PID='$id'",
"onstor",
$link);
}
}
And if the database type of QTYHAND and PID are int, exclude single quotes (') from your SQL queries.