Example of a Multi Condition Delete with Zend framework - php

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);

Related

mysql: wp database update

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);

How to set the conditionally Order_BY in rest AP

I want to set the conditionally Order_BY in rest API
e.g("B" comes before "A"and "D" comes before "C" means the out put is appear like this "BADC")
please help me if it is possible
$get_entry_list_parameters = array(
//session id
'session' => $session_id,
//The name of the module from which to retrieve records
'module_name' => 'Accounts',
//The SQL WHERE clause without the word "where".
'query' => $query,
//The SQL ORDER BY clause without the phrase "order by".
'order_by' => " How to set Conditional Order By "
);
I guess BADC that you mentioned is column's name.
That should be done with some code like this:
<?php
$order_by = $_POST['order_by']; // order_by's format is like this: B:asc;A:asc;D:desc;C:desc;
$order_by_str = ""; // to store a query statement for 'order by'
$order_by_array = explode(';', $order_by);
foreach ($order_by_array as $order_item) {
$order_item_array = explode(':', $order_item);
$order_by_str .= "," . $order_item_array[0] . " " . $order_item_array[1];
}
$order_by_str = substr($order_by_str, 1); // result for order_by
This is a known bug.
There is a bug report with a proposed fix here Defect 66206: REST V4_1 API,function get_entry_list didn't work with the order_by attribute
Applying the proposed fix worked for me.

PDO prepare/execute the table and append WHERE's

I'm trying to do the following:
public function checkResult($table, $appends)
{
$append = null;
foreach ($appends as $key => $val)
$append = " AND `{$key}` = '{$val}'";
$result = $this->fetchObj("
SELECT *
FROM :cms_table
WHERE id :append
", array(
":cms_table" => $table
":append" => $append
));
return ($result ? true : false);
}
But I can't get this working because I don't know how to do this in PDO.
Also when I leave the :append my query isn't working either. It looks like I can't execute a table. When I change :cms_table to the cms_pages (table I need) it works correctly.
I couldn't find a thing about such query's in PDO. Anyone who can help me out?
Don't try to outsmart yourself.
You don't need no checkResult() function, as well as no other function of similar structure.
$sql = "SELECT 1 FROM table WHERE field = ? AND col = ?";
$found = $db->fetchObj($sql, array(1,2));
is all you actually need.

MongoDb Collection 300K Objects Making an A to Z page

We have a website with about 300,000 people on it - what we want to do is make an page with all the peoples name that starts with A, B, or C.
The challenge is the speed.
How would you set up your database. Do you make a cache collection. Do you use regex or something else.
What i've done is the following;
$letter = 'A';
$where = array();
$where['name'] = new MongoRegex("/^" . $letter . "/i");
$sort = array('name' => 1);
if($hasImage){
$where['images.profiles.0'] = array('$exists' => true);
}
$fields = array('name' => 1, 'images.profiles' => 1);
$this->mdb->data_people->ensureIndex(array('name' => 1, 'images.profiles' => 1), array('background' => true) );
$people = $this->mdb->data_people->find( $where, $fields );
$people = $people->sort( $sort );
$page['total'] = 100;
$page['current'] = 1;
$page['perPage'] = 20;
if(isset($this->domain->getQuery['_page']) && $this->domain->getQuery['_page'] > 1){
$page['current'] = $this->domain->getQuery['_page'];
}
$data['pages'] = $this->pageNavigation->setNavigation((int) $page['total'], (int) $page['perPage'], (int) $page['current'] );
$data['pages']['page'] = $this->domain->menu_reverse[0];
$data['pages']['path'] = $this->domain->path;
$data['data'] = $people->limit($page['perPage'])->skip( ($page['perPage']*($page['current']-1)) );
You are pretty much doing the right thing.
You are even using the right regexp since it look only for the start of the string, and so Mongodb can use the name index.
see bottom of this page: http://docs.mongodb.org/manual/reference/operator/query/regex/)
I see only two potential problems (but as always: don't do premature optimization, you'll code can be just fine as is):
the case-insensitive modifier in the regexp: try using a strtolower-ed field insted (create a nameCanonical field with the lowercase version of the name field.)
the pagination, which is always slow: try using a range-based pagination http://docs.mongodb.org/manual/reference/method/cursor.skip/

Building a PDO MYSQL query from a php arrays?

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);

Categories