Hey all i normally grab the ajax sent js object literal by doing this:
$_POST['called']
$_POST['chk1']
etc etc...
But now i have a problem that i cant seem to find a solution for.
Depending on how many checkboxes are selected, i loop (using js) to see all checked boxes and add them to the js object that ends up looking like this:
doBulk = {
called: "Approved",
chk0: "1789156857",
chk2: "5134465673753",
chk3: "234123554646",
chk10: "25511545542"
};
Now the chkXX can be any number from 0-19 (so 20 check boxes per page). I am sending that just fine to my PHP page but i am unsure on how to go about looping to get the needed data to update the database.
$chk1 = $_POST['chk0'];
$chk2 = $_POST['chk1'];
$chk3 = $_POST['chk2'];
$chk4 = $_POST['chk3'];
$chk5 = $_POST['chk4'];
$chk6 = $_POST['chk5'];
$chk7 = $_POST['chk6'];
$chk8 = $_POST['chk7'];
$chk9 = $_POST['chk8'];
$chk10 = $_POST['chk9'];
$chk11 = $_POST['chk10'];
$chk12 = $_POST['chk11'];
$chk13 = $_POST['chk12'];
$chk14 = $_POST['chk13'];
$chk15 = $_POST['chk14'];
$chk16 = $_POST['chk15'];
$chk17 = $_POST['chk16'];
$chk18 = $_POST['chk17'];
$chk19 = $_POST['chk18'];
$chk20 = $_POST['chk19'];
I could do a lot of if than else to check to see if each has data but there has got to be a better way of doing that?
So if i am doing a bulk mySQL update then i would have to run a query for each checkbox that i have a value for above? Is there also a better way of updating all the records that are needed in one swoop?
$result = mysql_query("UPDATE userAccount SET Accept = 1 WHERE ID = " . $chk1 . "");
Thanks!
UPDATE
foreach($_POST as $key => $value)
{
// $key = CHK1-20
// $value = XXXXXXXXX
$dbBuilder = $value . ", " . $dbBuilder;
}
$dbBuilder = '(' . $dbBuilder . ')';
$result = mysql_query("UPDATE userAccount SET Accept = 1 WHERE ID in $dbBuilder");
You can pass in the id's inside an IN SQL Clause. So, for instance you will have:
UPDATE userAccount SET Accept = 1 WHERE ID in $idCollection
Where $idCollection will be all of the IDs checked, separated by commas and inside parentheses, like so:
(1, 2, 3)
For the looping, you can iterate through the $_POST array as you would in any other array, and populate this string with the values read.
Hope that helps
for ($i=1;$i<=20;$i++){
${'chk'."$i"}=$_POST["chk"."$i"];
}
For UPDATE, i think you can use Mysql create procedure like this
$query=mysql_query("CREATE PROCEDURE dorepeat(p1 INT) SET $i = 0; REPEAT SET #i = #i + 1; UPDATE userAccount SET Accept = 1 WHERE ID = ${'chk'."$i"}; UNTIL #i =p1 END REPEAT; END") or (die mysql_error());
$result=mysql_query("CALL dorepeat(20)") or (die mysql_error());
EDIT: perhaps this is better without using CREATE PROCEDURE.
for ($i=1;$i<=20;$i++){
${'chk'."$i"}=$_POST["chk"."$i"];
$exp.=${'chk'."$i"}.',';
}
$exp=substr($exp,0,-1);
$exp='('.$exp.')';
$query=mysql_query("UPDATE userAccount SET Accept = 1 WHERE ID IN '$exp') or (die mysql_error());
Related
I have a web application and I'm trying to modify one of the queries. The query fetches information (from a table named voyage_list) and returns various fields.
I want to modify the query so that it is based on certain filters the user applies (which will be placed in the URL).
I can't get the query to work in the web application, but if I copy the query and execute it directly within PHPMyAdmin, it works fine.
$vesselFilter = $_GET['vesselFilter'];
$vesselArray = explode(',', $vesselFilter);
$arrayCount = count($vesselArray);
$sqlExtend = ' status = 1 AND';
foreach ($vesselArray as $value) {
$i = $i + 1;
$sqlExtend .= " vesselID = '$value'";
if ($i < $arrayCount){
$sqlExtend .= " OR";
}
}
$newQuery = "SELECT * FROM voyage_list WHERE" . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
I appreciate the above is pretty messy, but it's just so I can try and figure out how to get the query to work.
Any help would be greatly appreciated!
Thanks
That query probably doesn't return what you think it does. AND takes precedence over OR, so it will return the first vessel in the list if the status is 1, and also any other vessel in the list, regardless of status.
You'd do better to create a query with an IN clause like this:
SELECT * FROM voyage_list WHERE status = 1 AND vesselID IN(8,9,10)
Here's some code to do just that:
$vesselFilter = $_GET['vesselFilter'];
// Validate data. Since we're expecting a string containing only integers and commas, reject anything else
// This throws out bad data and also protects against SQL injection.
if (preg_match('/[^0-9,]/', $vesselFilter)) {
echo "Bad data in input";
exit;
}
// filter out any empty entries.
$vesselArray = array_filter(explode(',', $vesselFilter));
// Now create the WHERE clause using IN
$sqlExtend = 'status = 1 AND vesselID IN ('.join(',', $vesselArray).')';
$newQuery = "SELECT * FROM voyage_list WHERE " . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
var_dump($query);
i have this sql query written in php:
$query = sprintf("UPDATE bank_info SET
amount_dollar = amount_dollar +'$amount_dollar' ,
amount_euro = amount_euro + '$amount_euro' ,
amount_local = amount_local + '$amount_local'
WHERE bank_id = '$bank_id' ");
this query works fine, but i want to transform this query using FluentPDO.
i want to use arrays to SET the values .
for example:
$table='bank_info'; //table name
$arrVal=array(); //values needs to be SET
$arrVal['amount_dollar = amount_dollar+?']=$amount_dollar;
$arrVal['amount_euro = amount_euro+?']=$amount_euro;
$arrVal['amount_local = amount_local+?']=$amount_local;
$arrWhere=array(); //where condition
$arrWhere['bank_id']=$bank_id;
this is the query:
$query = $this->pdo->update($table)->set($arrVal)->where($arrWhere);
$query->execute();
I think the problem is in the $arrVal, cant find the proper way to SET and add value to the current value for a column in the table.
I used array to select and get values from the DB/tables for many times so i think the $arrWhere is not the problem.
well, found the answer,
for ex.:
This is working for me:
$id = 5;
$field = 'stock';
$amount = 1;
$increment = array($field => new FluentLiteral($field.' + '.$amount));
$fpdo->update('products')->set($increment)->where('id', $id)->execute();
$query = "select Code , count(ListID) as nums from accesstable where Cust=" . $_SESSION ['Cust'] . " and App=" . $_SESSION ['App'] . " group by Code";
$result = mysql_query ( $query );
while ($row = mysql_fetch_array ( $result )){
$Codes[] = $row['Code'];
$Values[] = $row['nums'];
}
This is the structure of my code that I am trying to learn how to properly access... Here is my dilemma... I am trying to figure out how to explicitly find the associated count of nums dependent on the value of a Code.
Let me explain in better detail where my issue is....
Lets say the list of codes is
Code nums
1 624
7 825
571 450
9 393
2 739
9 590
The above code does successfully allow me to separate those values strictly into keys and values but I cannot figure out how to grab the nums value if the code is = to a certain value... I have currently been trying to declare a variable above the entire snippet of code and then declare it within the while statement but cannot figure out how to get the value to bind properly.... I will repaste the above code with one of my many failures in the while statement to give a better idea.
$Answer1 = 0;
$query = "select Code , count(ListID) as nums from accesstable where Cust=" . $_SESSION ['Cust'] . " and App=" . $_SESSION ['App'] . " group by Code";
$result = mysql_query ( $query );
while ($row = mysql_fetch_array ( $result )){
$Codes[] = $row['Code'];
$Values[] = $row['nums'];
($Codes == 1){
$Answer1 = // Right Here I want to Get the value 624 related to Code 1... Dont want to embarass myself with examples of what I have tried...
}
So how do I make a condition to output the value associated with a Code? I want to explicitly define these values as the list of codes can change with each customer... Luckily there are only a certain amount of codes so its not like I need to define too many of them... I just want to make sure I can get the nums value associated with a code and display it.
Hope I did a good job explaining this. :)
I'd do:
while ($row = mysql_fetch_array ( $result )){
$Codes[] = $row['Code'];
$Values[$row['Code']] = $row['nums'];
}
and, to access the value associated to a code:
$code = 1;
$value = $values[$code];
Since they would share the same array key, something like this would work-
if ($Codes[$key] == 1){
$Answer1 = $Values[$key];
}
I have a members site where users are given up to 7 web page templates to display their products on. Each template has the same field names, differentiated by _1, _2... _7 at the end of each.
For example:
// Template 1 would have the following list of variables
product_name_1
product_descript_1
product_color_1
product_price_1
// Template 2 would have the following list of variables
product_name_2
product_descript_2
product_color_2
product_price_2
// through Template 7
I am able to display any variables for a specific user within a web page, by use of a query string identifying their user_id in the url, ie
http://domain.com/folder/page.php?id=78
I then $_Get any variable by simply identifying it in the PHP file, ie
$product_name_1
$product_descript_1
$product_color_1
$product_price_1
My problem is that the url must identify WHICH template, since each template identifies a specific product, ie _1, _2, ..._7. How do I use a parameter in the url, such as
http://domain.com/folder/page.php?id=78¶meter=_7
...to identify all variables ending with _7, which would appear in the web page? The parameter used in the url would identify the variables to be used in the web page, whether _1, _2, etc.
UPDATE
I have tried the various answers with only partial success, ie "Array_x" is displayed when using any particular variable along with the suggested code. There may be a conflict with the rest of the code I'm using in page.php, as follows:
$db_connection = new mysqli("", "", "");
if ($db_connection->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
$prop_address=array(
"_1"=>"prop_address_1",
"_2"=>"prop_address_2",
"_3"=>"prop_address_3"
//Through to Temp 7
);
$prop_address{$_GET['parameter']}=$row->prop_address;
echo " $prop_address{$_GET['parameter']} ";
"Array_x" displays (where x=1, 2, 3, etc is used as the parameter in url, ie http://domain.com/page.php?id=72¶meter=1), instead of the actual value held in the database table for $product_name{$_GET['parameter']}. For some reason, the code is not picking up the value of the variable from the database table.
Would it be possible to use arrays so...
$product_name=array(
"1"=>"Product name for template 1",
"2"=>"Product name for template 2"
//Through to Temp 7
);
echo $product_name[$_GET["parameter"]];
You could then do the same for the other variables.
You could fill each array by doing something like:
$row = mysql_fetch_object($query);
$product_name[$_GET['parameter']]=$row->product_name;
echo $product_name[$_GET['parameter']];
I may be missing something...
$_GET['parameter'] = '_2';
$product_name{$_GET['parameter']} = 'string';
echo $product_name_2; // string
or
$_GET['parameter'] = '_2';
$var = 'product_name'.$_GET['parameter'];
$$var = 'string';
echo $product_name_2; // string
Personally, I would use array's for this type of behavior.
Update:
Although the above works and tested ok, it is a lot more work than anyone would probably desired.
In lieu of simplicity, I would suggest the approach via array's.
$templates = array(2 => array(
'product_name' => "value",
'product_descript' => "value",
'product_color' => "value",
'product_price' => "value",
);
foreach($templates[substr($_GET['parameter'],1)] as $var => $val){
$variable = $var.$_GET['parameter'];
$$variable = $val;
}
The above is backwards compatible, it uses substr to remove the leading _ from your parameter.
I couldn't get any of the answers given to work. I found an example given by a user for php variable variables in the PHP manual here and found it to work. I incorporated it into my code as follows:
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
for( $i = 1; $i < 8; $i++ )
{
$product_name[$_GET['parameter']] = "product_name_" . $i;
$product_descript[$_GET['parameter']] = "product_descript_" . $i;
$product_color[$_GET['parameter']] = "product_color_" . $i;
$product_price[$_GET['parameter']] = "product_price_" . $i;
}
${$product_name[1]} = "$row->product_name_1";
${$product_name[2]} = "$row->product_name_2";
${$product_name[3]} = "$row->product_name_3";
${$product_name[4]} = "$row->product_name_4";
${$product_name[5]} = "$row->product_name_5";
${$product_name[6]} = "$row->product_name_6";
${$product_name[7]} = "$row->product_name_7";
// List 7 variables and values for each field name
echo "${$prop_name[$_GET['par']]}";
The only problem is that mysql injection is possible with this code. If anyone could suggest a solution, I would greatly appreciate it.
i am doing a project where one may update the name, position, department and tag of the employee.
But as i do my project, it wont update, i know there is something wrong with my code. would you guys mind checking it.
my php page has an index.php which is the main menu, if you click the employee name in the list, a pop up window will appear. that pop up is for updating.
my php code (it now updating) but errors found:
<?php
$con=mysql_connect('localhost','root','pss') or die(mysql_error());
mysql_select_db('intra',$con);
if(isset($_POST['submitted']))
{
$sql = "SELECT * FROM gpl_employees_list where emp_id='".$_POST['eid']."'";
$result = mysql_query($sql) or die (mysql_error());
if(!$result || mysql_num_rows($result) <= 0)
{
return false;
}
$qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['ename']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_POST['eid']."' ";
mysql_query($qry) or die (mysql_error());
?><script>window.close();</script><?php
}
?>
*NOTE : this is now updating, but if a user leaves one of the textboxes empty, it updates the table with empty spaces as well and that is my problem now. how do i avoid that? i mean if a user leaves one textbox empty,the data with empty values must still contain its old value,but how to do that with this code? thanks for those who will help
MisaChan
You use $_POST for 'name/pos/dep/tag' and $_GET for 'emp' so you're probably not getting the values.
Change the GETs to POST - that should do it.
Since you're updating, I'd recommend using POST over GET.
GET is more appropriate for searching.
Also, you can put all your update queries into one update query.
Like so.
$name = $_POST['name'];
$pos = $_POST['pos'];
$dep = $_POST['dep'];
$tag = $_POST['tag'];
$emp = $_POST['emp'];
$qry_start = "UPDATE gpl_employees_list SET ";
$where = " WHERE emp_id = $emp";
$fields = "";
$updates = "";
if($name){
$updates .= " `emp_name` = $name,";
}
if($pos){
$updates .= " `emp_pos` = $pos,";
}
if($dep){
$updates .= " `emp_dep` = $dep,";
}
if($tag){
$updates .= " `emp_tag` = $tag,";
}
$updates = substr($updates, 0, -1); //To get rid of the trailing comma.
$qry = $qry_start . $updates . $where;
this is what i used to keep it working :) i hope this could be a source for others as well :)
$col['emp_nme'] = (trim($_POST['ename']))?trim($_POST['ename']):false;
$col['emp_pos'] = (trim($_POST['pos']))?trim($_POST['pos']):false;
$col['emp_dep'] = (trim($_POST['dep']))?trim($_POST['dep']):false;
$col['emp_tag'] = (trim($_POST['tag']))?trim($_POST['tag']):false;
// add a val in $col[] with key=column name for each corresponding $_POST val
$queryString ="UPDATE `gpl_employees_list` SET ";
foreach($col as $key => $val){
if($val){
$queryString .="`".$key."`='".$val."',";
}
}
$queryString = substr($queryString ,0 ,strlen($queryString) - 1 )." WHERE emp_id = '".$_POST['eid']."'";
mysql_query($queryString);
After making changes to an SQL database, remember to commit those changes, otherwise they'll be ignored.