I am trying to build a query from the values of an array so far I have,
$itemPlus = $_POST['itemPlus'];
$query = implode(', ', array_map(function($items) {return $items . ' = ' . $items . '-?';}, $items));
// $query = 'hats = hats-?, gloves = gloves-?, scarfs = scarfs-?'
$params = implode(', ', $userCost);
// $params = '10, 7, 9'
$q = $dbc -> prepare("UPDATE items SET " . $query . ", $itemPlus = $itemPlus+1 WHERE id = ?");
$q -> execute(array($params, $account['id']));
It doesn't work, this is my first time trying this and as it doesn't work I am obviously doing something wrong!?
Thanks
Since $params is a string of values, you cannot make it into an array along with $account['id']. Instead.use the array that created it $userCost:
// Start with the $userCost array...
$paramArr = $userCost;
// Add $account['id'] to it
$paramArr[] = $account['id'];
// And pass that whole array to execute()
$q -> execute($paramArr);
Since $itemPlus is coming from $_POST, you will need to be sure that is valid input. Since it refers to a column name, it is recommended to use a whitelist for that:
// Check against an array of possible column names:
if (!in_array($_POST['itemPlus'], array('col1','col2','col3','col4',...)) {
// $_POST['itemPlus'] is NOT VALID
// Don't proceed...
}
Your problem (one of them) lies here:
$q -> execute(array($params, $account['id']));
The $params variable is a comma-delimited string:
// $params = '10, 7, 9'
You want to pass an associate array of params and values to the execute() method, like this:
$params = array(
'hats-?' => 10,
'gloves-?' => 7,
'scarves-?' => 9
);
// ...
$q->execute($params);
Related
The code I've written so far works fine if there is only one named place holder for a prepared statement but if there are multiple conditions for a query, it doesn't return any results from the database.
For instance:
$query = array();
$query['columns'] = array('*');
$query['tables'] = array('esl_comments');
$query['where'] = array(
'esl_comments.commentVisible' => array('=', 'Y')
);
Works fine. But if I try:
$query = array();
$query['columns'] = array('*');
$query['tables'] = array('esl_comments');
$query['where'] = array(
'esl_comments.commentVisible' => array('=', 'Y'),
'esl_comments.commentID' => array('=', '1'),
);
(Note the additional commentID parameter) it fails to return anything despite there being data in the mySQL database that satisfies the conditions.
The PDO code i've written is:
$sql ='SELECT ';
foreach($query['columns'] as $column){ //What columnns do we want to fetch?
$sql.=$column . ", ";
}
$sql = rtrim($sql, " ,");
$sql .=' FROM '; //Which tables will we be accessing?
foreach($query['tables'] as $tables){
$sql.=$tables . ", ";
}
$sql = rtrim($sql, " ,"); //Get rid of the last comma
$sql .=' WHERE ';
if(array_key_exists('where', $query)) //check if a where clause was provided
{
$fieldnames = array_keys($query['where']);
$count = 0;
$size = sizeof($fieldnames);
$bindings = array();
foreach($query['where'] as $where){
$cleanPlaceholder = str_replace("_", "", $fieldnames[$count]);
$cleanPlaceholder = str_replace(".", "", $cleanPlaceholder);
$sql.=$fieldnames[$count].$where[0].":".$cleanPlaceholder." AND ";
$bindings[$cleanPlaceholder]=$where[1];
$count++;
}
$sql = substr($sql, 0, -5); //Remove the last AND
}
else{ //no where clause so set it to an always true check
$sql.='1=1';
$bindings=array('1'=>'1'); //Provide default bindings for the statement
}
$sql .= ';'; //Add the semi-colon to note the end of the query
echo $sql . "<br/><br/>";
// exit();
$stmt = $this->_connection->prepare($sql);
foreach($bindings as $placeholder=>$bound){
echo $placeholder . " - " . $bound."<br/>";
$stmt->bindParam($placeholder, $bound);
}
$result = $stmt->execute();
echo $stmt->rowCount() . " records<br/>";
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
I'm building queries dynamically and therefore I am cleaning the placeholders, by stripping them of periods and underscores - hence the use of the 'cleanPlaceholder' variable.
The query being generated looks like this:
SELECT * FROM esl_comments WHERE esl_comments.commentVisible=:eslcommentscommentVisible AND esl_comments.commentID=:eslcommentscommentID;
And the parameters being bound look like this:
eslcommentscommentVisible - Y
eslcommentscommentID - 1
bindParam Requires a reference
The problem is caused by the way you bind parameters in the foreach loop.
foreach($bindings as $placeholder=>$bound){
echo $placeholder . " - " . $bound."<br/>";
$stmt->bindParam($placeholder, $bound);
}
bindParam requires a reference. It binds the variable, not the value, to the statement. Since the variable in a foreach loop is reset at the start of each iteration, only the last reference to $bound is left intact, and you end up binding all your placeholders to it.
That's why your code works when $query['where'] contains only one entry, but fails when it contains more than one.
You can solve the problem in 2 ways:
Pass by reference
foreach($bindings as $placeholder => &$bound) { //pass $bound as a reference (&)
$stmt->bindParam($placeholder, $bound); // bind the variable to the statement
}
Pass by value
Use bindValue instead of bindParam:
foreach($bindings as $placeholder => $bound) {
$stmt->bindValue($placeholder, $bound); // bind the value to the statement
}
So, I have a following js and php:
JS:
var names = jQuery('#name').val();
data : {'action':'AJAX' , name:names },
The #name values are "mike,sean,steve"
PHP:
global $wpdb;
$names = $_POST['name'];
$table = $wpdb->prefix . 'my_name';
$RSS_UPDATE = $wpdb->get_col("SELECT update_number FROM $table WHERE id_name IN ($names)");
//update_number are int (example: 0,3,1,2)
$name = explode(',', $names);
if ( $RSS_UPDATE ){
foreach ( $RSS_UPDATE as $RSS_SINGLE ){
$RSS_ROW_NEW = $RSS_SINGLE + 1;
$wpdb->update($table, array('update_number' => $RSS_ROW_NEW),array( 'id_name' => $name));
}
}
So, few things:
what I am trying to achieve:
With the input values, get corresponding update_number. Then increase each value by "1" and update the same column with the new value.
Errors
Unknown column 'Array' in 'where clause' for query SELECT update_number FROM wp_my_name WHERE id_name IN (Array)
Just in general, something is not right...
Can someone help me out?
Thank you.
EDIT:
Does this look right?
if(!empty($_POST['name'])) {
$names = $_POST['name']; //array
$table = $wpdb->prefix . 'rh_subs';
$query = "SELECT update_number FROM $table WHERE id_name = %s";
$RSS_UPDATE = $wpdb->get_results($wpdb->prepare($query, $names));
if(!empty($RSS_UPDATE)) {
foreach($RSS_UPDATE as $RSS_SINGLE) { // for each row
$RSS_ROW_NEW = $RSS_SINGLE->update_number + 1;
$wpdb->update($table, array('update_number' => $RSS_ROW_NEW),array('id_name' => $RSS_SINGLE->id_name));
}
}
}
Just what I've said in the comments in your earlier post, since you're taking multiple inputs, you'll need to use the WHERE IN clause.
The simple example would be like this:
$_POST['name']; // these are comma delimited string of names
// "mike,sean,steve"
So in essence, you'll need to construct them inside a WHERE IN clause like this:
WHERE id_name IN ('mike', 'sean', 'steve')
The unsafe and dirtiest way would be to just explode - put quotations on the strings - implode it back together with comma again:
$names = array_map(function($e){
return "'$e'";
}, explode(',', $test));
$names = implode(',', $names);
// 'mike','sean','steve' // SATISFIES WHERE IN CLAUSE
// BUT UNSAFE!
So in order to do this safely, use the wpdb prepared statements. (This could get you started).
if(!empty($_POST['name'])) {
$names = explode(',', $_POST['name']); // explode the comma delimited string into an array
$table = $wpdb->prefix . 'my_name';
$stringPlaceholders = implode(', ', array_fill(0, count($names), '%s')); // create placeholders for the query statement, this will generate
$statement = $wpdb->prepare("SELECT update_number, id_name FROM $table WHERE id_name IN ($stringPlaceholders)", $names); // create the statement using those placeholders
$RSS_UPDATE = $wpdb->get_results($statement); // execute
// fetch resuls
if(!empty($RSS_UPDATE)) {
foreach($RSS_UPDATE as $RSS_SINGLE) { // for each row
$RSS_ROW_NEW = $RSS_SINGLE->update_number + 1;
$wpdb->update($table, array('update_number' => $RSS_ROW_NEW),array('id_name' => $RSS_SINGLE->id_name));
}
}
}
Note: Of course you can get creative yourself. I think you could combine the UPDATE and WHERE IN clause so that you'll just execute all of this once.
First of all, It seems that $_POST['name'] returns an array.
You can view what exactly you are getting in $_POST['name'] by:
var_dump($_POST['name'], true);
Also For the id_name, if they are like these "mike,sean,steve" then you should do this for adding quotes for strings and the escaping issue so that they can be like this "'mike','sean','steve'" as you are using a WHERE IN clause:
$names = $_POST['name'];
if(!is_array($names)) $names = explode(",",$names);
$new_names = array();
foreach($names as $name){
$name = get_magic_quotes_gpc() ? stripslashes($name) : $name;
$new_names[] = "'".mysql_real_escape_string($name)."'";
}
$names = implode(",", $new_names);
I'm trying to build a custom class to manage operations with database. I'm a beginner with OOP so if you have any suggests please tell me. By the way, i have an update method which took as parameter the name of the table, the fields to update, the values with which i want to update the fields and the fields and values to put in where clause of query.
At this time, i have two distinct arrays, one for the set part and one for the where part.
I build the query string like so PDOStatement Object ( [queryString] => UPDATE Ordini SET Nome=':Nome', Cognome=': Cognome', Telefono=': Telefono' WHERE ID=':ID' )
Now i would like to bind the params to the variables and execute the query and that's the problem. I try this way but the query don't update the fields.
- In $values i have the values i want to bind to variables in the SET part
- In $wv i have the values i want to bind to variables in the WHERE part
- In $fieldsQuery i have the placeholders for the SET part(":Nome" for example)
- In $fieldsWhere i have the placeholders for the WHERE part
How can i bind in the right way the placeholders with the variables?
public function update($table=NULL, $fieldsQuery=NULL, $fieldsValues = NULL, $whereFields=NULL, $whereValues=NULL, $whereOperators = NULL)
{
if($fieldsQuery != NULL)
$fields = explode(",", $fieldsQuery);
if($fieldsValues != NULL)
$values = explode(",", $fieldsValues);
if($whereFields != NULL)
$wf = explode(",", $whereFields);
if($whereValues != NULL)
$wv = explode(",", $whereValues);
$fieldsQuery = array_map(function($field) { return ":$field";}, $fields);
$bindValuesSet = array_combine($fieldsQuery, $values);
//return an array in which every field is => Fieldname=':Fieldname'
$bindSetInitial = array_combine($fields, $fieldsQuery);
//transform every item in array from field to :field
$fieldsWhere = array_map(function($field) { return ":$field";}, $wf);
$bindValuesWhere = array_combine($fieldsWhere, $wv);
$bindWhereInitial = array_combine($wf, $fieldsWhere);
//implode an array mantaining both key and value
$fieldsValues = implode(', ', array_map(function ($v, $k) { return sprintf("%s='%s'", $k, $v); }, $bindSetInitial, array_keys($bindSetInitial)));
$fieldsWhere = implode(', ', array_map(function ($v, $k) { return sprintf("%s='%s'", $k, $v); }, $bindWhereInitial, array_keys($bindWhereInitial)));
$query = $this->db->prepare('UPDATE ' . $table . ' SET ' . $fieldsValues . ' WHERE ' . $fieldsWhere);
$query->bindParam(':Nome', $values[0]);
$query->bindParam(':Cognome', $values[1]);
$query->bindParam(':Telefono', $values[2]);
$query->bindParam(':ID', $wv[0], PDO::PARAM_INT);
$query->execute();
print_r($query->debugDumpParams());
}
':Nome' is not a placeholder for a prepared statement. It's just a string ':Nome'
Placeholder is :Nome (without `) and without any spaces, tabs etc.
I.e. : Nome is not a placeholder too.
So, you query should be:
UPDATE Ordini SET Nome=:Nome, Cognome=:Cognome, Telefono=:Telefono WHERE ID=:ID
And thanks to #Fred-ii- - read error handling section of PDO
This is sort of a follow up to my last question. Im trying to access the data of a multidimensional array so as to insert into a database. Ive been looking all over the forums as well as trying different things on my own but cant find anything that works. Here is what the array looks like:
$_POST[] = array[stake](
'stakeholder1' => array(
'partner'=> 'partner',
'meet'=> 'meet'
),
'stakeholder2' => array(
'partner'=> 'partner',
'agreement'=> 'agreement',
'train'=> 'train',
'meet'=> 'meet'
),
);
I'm trying to do somthing like ( UPDATE list WHERE stakeholder = "stakeholder1" SET partner =1, meet =1 ) depending on which stakeholder/choices were selected (theres four different options). Thanks,
This one will set 1 for checked options, and 0 for unchecked options (otherwise you will miss some data updates).
$optionsList = array('partner', 'agreement', 'train', 'meet');
$stakeHolders = array('stakeholder1', 'stakeholder2', ...);
foreach($stakeHolders as $stakeHolder)
{
$selectedOptions = $_POST[$stakeHolder];
$arInsert = array();
foreach($optionsList as $option)
$arInsert[] = '`'.$option.'` = '.intval(isset($selectedOptions[$option]));
$sql = "UPDATE list
SET ".implode(", ", $arInsert)."
WHERE stakeholder = '".mysql_real_escape_string($stakeHolder)."'";
// TODO: execute $sql (mysql_query(), or PDO call,
// or any wrapper you use for DB)
}
$query = '';
foreach ($_POST as $k => $v) {
$query .= "UPDATE list WHERE stakeholder = '$k' SET " . implode(" = 1," $v) . ",";
}
$query = substr($query, 0, -2); //Get rid of the final comma
This should give you something like what you are looking for, if I understand your database schema correctly.
If you are using PDO, you could do something like:
foreach($_POST as $stakeholder => $data) {
$sth = $dbh->prepare('UPDATE `list` SET `' . implode('` = 1, `', array_keys($data)) . '` = 1 WHERE stakeholder = ?');
$sth->execute(array($stakeholder));
}
Be sure to sanitize the user input (keys of the data...).
foreach($main_array as $key => $sub_array) {
$sql = 'UPDATE list
WHERE stakeholder = "{$key}"
SET ';
$sets = array();
foreach($sub_array as $column_value)
$sets[] = $column_value." = 1";
$sql = $sql.implode(',', $sets);
}
Can someone give me an example of how I would delete a row in mysql with Zend framework when I have two conditions?
i.e: (trying to do this)
"DELETE FROM messages WHERE message_id = 1 AND user_id = 2"
My code (that is failing miserably looks like this)
// is this our message?
$condition = array(
'message_id = ' => $messageId,
'profile_id = ' => $userId
);
$n = $db->delete('messages', $condition);
Better to use this:
$condition = array(
'message_id = ?' => $messageId,
'profile_id = ?' => $userId
);
The placeholder symbols (?) get substituted with the values, escapes special characters, and applies quotes around it.
Instead of an associative array, you should just be passing in an array of criteria expressions, ala:
$condition = array(
'message_id = ' . $messageId,
'profile_id = ' . $userId
);
(and make sure you escape those values appropriately if they're coming from user input)
Use this , it is working...
$data = array(
'bannerimage'=>$bannerimage
);
$where = $table->getAdapter()->quoteInto('id = ?', 5);
$table->update($data, $where);