conversion of mongodb into php with 'and' - php

I have long query on mongodb. I want to write that in php
The query looks like
"department":"xxx","rank":"xxx",
$and:[{"emails.email" :{$ne : ""}},{"emails.email":{$ne:null}}];
I want to convert into php.
"department"=>$xxx,"rank"=>$xxx..??
for converting 'and' I cant come up. please help

The best way to work with the $ modifiers is to use single quotes as seen below. It's close on the syntax however you will want to double check it as I'm certain there may have been a missed bracket.
array(
'department'=>'',
'rank=>'',
'$and'=>array(
'emails.email'=>array('$ne'=>''),
'emails.email'=>array('$ne'=>NULL)
)
);
Good Luck!

You can commit the query that #Frederico wrote however this query could do with some optimisation. Here is a suggestion:
array(
'department' => '',
'rank' => '',
'emails.email' => array('$nin' => array('', null))
)
That will do the job just as good without the $and and the two separate $ne.

Related

Preparing a SQL statement that contains paired single and double quotes in PHP

Here goes. I have a 200-line MySQL query that contains six different Excel formulas in one of the columns, like this:
SELECT '%%%=""Greg''s #""&INDIRECT(""G""&ROW()&""#"")' AS 'Location'
This code snippet will run correctly in MySQL, and because of the doubled-up punctuation, can be exported to a CSV without causing havoc in the CSV. However, now I have to put this query into a prepared statement in PHP as part of the process of automating my company's (you guessed it, Excel-based) reporting. How do I harden the prepared statement against all the doubled punctuation?
I've tried escaping with a \ before each quotation mark, but this somehow causes the MySQL query to return only the Excel formulas, and not the database data that has to go alongside it. Same with heredoc. PDO::quote() didn't even get me that far. I half suspect there's a way to use fputcsv to get around the problem, but I assume I have to prepare the statement before bringing fputcsv into the fray. (Not saying I've done any of these the correct way; I'm trying whatever Google says to try at this point.) So far, no queries have returned in PHP what they do in SQL.
The various data I care about exist in all three formats (and more besides...), and have to be collected as I go downstream, in this case from PHP to MySQL to an emailed CSV to a VBA-automated Excel report. My company thinks of data storage solutions like Pokémon. Gotta subscribe to them all. So this is a problem I can't just dodge.
Thank you, kind people. I'm doing my utmost to get our reporting under control, but this challenge has so far proved un-Googleable (probably because Google doesn't understand "double double quotes" or "paired double quotes").
HEREDOC does the trick. The following code does not get mangled:
$csv_fields = array("Location","Location ID","Region","Area","Area #","Client","Store #","Signature","AM","AR","AA");
$TechExport = <<<Your_HEREDOC_Tag
SELECT
a.location AS 'Location'
, '%%%=FILTER(''Store Admin''!A:A,(''Store Admin''!A:A<>''Store Admin''!A1)*(''Store Admin''!A:A<>""))' AS 'Location ID'
, '%%%=INDEX(''Store Admin''!B:B,XMATCH(INDIRECT("B"&ROW()&"#"),''Store Admin''!G:G))' AS 'Region'
, '%%%=INDEX(''Store Admin''!C:C,XMATCH(INDIRECT("B"&ROW()&"#"),''Store Admin''!G:G))' AS 'Area'
, '%%%=INDEX(''Store Admin''!D:D,XMATCH(INDIRECT("B"&ROW()&"#"),''Store Admin''!G:G))' AS 'Area #'
, '%%%=INDEX(''Store Admin''!E:E,XMATCH(INDIRECT("B"&ROW()&"#"),''Store Admin''!G:G))' AS 'Client'
, '%%%=INDEX(''Store Admin''!F:F,XMATCH(INDIRECT("B"&ROW()&"#"),''Store Admin''!G:G))' AS 'Store #'
, '%%%=FILTER(UNIQUE(FILTER(SORTBY(FILTER(''Requests''!I:M,(ISNUMBER(''Requests''!F:F))),FILTER(''Requests''!F:F,(ISNUMBER(''Requests''!F:F)))),{1,0,0,0,1})),{0,1})' AS 'Signature'
, '%%%=INDEX(''Store Admin''!P:P,XMATCH(INDIRECT("B"&ROW()&"#"),''Store Admin''!G:G))' AS 'AM'
, '%%%=SUMIFS(''Requests''!H:H,''Requests''!M:M,INDIRECT("B"&ROW()&"#"),''Requests''!I:I,INDIRECT("S"&ROW()&"#"))' AS 'AR'
, '%%%=SUMIFS(''Assembly''!F:F,''Assembly''!A:A,INDIRECT("B"&ROW()&"#"),''Assembly''!E:E,INDIRECT("S"&ROW()&"#"))' AS 'AA'
FROM
`full-database-name`.location a;
Your_HEREDOC_Tag;
$preparedSQL = $db->prepare($SQL);
$preparedSQL->execute();
$results = $preparedSQL->fetchAll(PDO::FETCH_ASSOC);
$f = fopen('./test/Results.csv', 'w+');
fputcsv($f,$csv_fields);
foreach ($results as $result)
{
fputcsv($f,$result);
}
fclose($f);
I needed to do three things to convert my SQL code to a prepared statement:
First, put the HEREDOC tag around the entire SQL code block.
Second, fully qualify the SQL table references.
Third, turn the paired double quotes into normal double quotes (""this"" into "this"). Single quotes stay paired (''like this''). I assume this is the fputcsv function preserving the double quotes during the CSV creation, where in MySQL I had to preserve them by doubling them up, but honestly this is just a guess.

Mysql Insert PHP colons, semi colons and double quotes

i am writing a custom script to insert data into a wordpress database. The database contains an address section and the data in the field has various colons, semi colons and double quotes. I am having a hard time trying to write the php mysql insert statement. Getting a lot of syntax errors.
The Field looks like:
a:9:{s:8:"address1";s:7:"street1";s:8:"address2";s:7:"street2";s:4:"city";s:9:"London";s:5:"state";s:5:"Bucks";s:11:"postal_code";s:8:"MK49 8UY";s:7:"country";s:2:"GB";s:13:"logo_image_id";s:1:"0";s:5:"notes";s:0:"";s:12:"instructions";s:0:"";}
Can anyone offer any guidance on how to escape such a large number of characters
As Roberto Suggests - if you are attempting to insert a pre formatted serialized array into your database (and it has an error) it's not going to work. If you are collecting all the data individually and building it the simpler way to go about this would be to first construct the array, then convert it to a format that can be stored in the database easily (serialised arrays). Example:
$address = array(
'address1' => 'Street1',
'address2' => 'Street2',
'city' => 'London',
'state' => 'bucks',
'postal_code' => 'MK49 8UY',
'country' => 'GB',
);
$formattedAddress = serialize($address);
// returns
// a:6:{s:8:"address1";s:7:"Street1";s:8:"address2";s:7:"Street2";s:4:"city";s:6:"London";s:5:"state";s:5:"bucks";s:11:"postal_code";s:8:"MK49 8UY";s:7:"country";s:2:"GB";}
You can now reference $address within your insert statement to get a correctly formatted serialized array.

How to search in more than one column of the database using cakephp

Good morning,
I need some help in a survey, which I am not able to do.
Imagine a web application (php), which makes use cakephp.
In this application I have a search field, one normal input.
And imagine that this application has a table in the database with 3 fields, (produtoNome), (categoria), (tags).
how can this research below, I already search for table field (produtoNome).
$this->Anuncio->find('all',array('conditions' => array('produtoNome'=> array('$regex' => (string)$pesq))));
The question is:
How can I do a search, that search the 3 fields of the table not only one?
In other words, when someone types something into the search field, it will perform this search in more than one field of the table.
I tried this:
$produtos = $this->Anuncio->find('all',
array('conditions' =>
array('OR' =>
array(
array('produtoNome'=> array('$regex' => (string)$pesq)),
array('categoria'=> array('$regex' => (string)$pesq))
)
),
)
);
but does not work. Returns nothing.
$produtos = $this->Anuncio->find('all',
array('conditions' =>
array('OR' =>
array(
'produtoNome'=> array('$regex' => (string)$pesq),
'categoria'=> array('$regex' => (string)$pesq)
)
),
)
);
Not sure, but this should do the trick.
I would love to see the query from cake.
Never seen that '$regex' syntax for cake, can't find it in documentation, can't find any reference on the internet - where did you get that from? I'm using cake quite a while now and never came about that (though I never needed regexp for queries)
[sorry, low reputation, could not put this on a comment]
So, I got to do this research.
To work, so I had to modify the 'OR' to '$or'

How get normal SQL query from cake query array?

I have array like this
$conditions = array("Post.title" => "This is a post");
And using $conditions array in this method.
$this->Post->find('first', array('conditions' => $conditions));
I want convert the $conditions array to normal sql query.
I want use
$this->Post->query($converted_query);
instead of
$this->Post->find('first', array('conditions' => $conditions));
$null=null;
echo $this->getDataSource()->generateAssociationQuery($this, NULL, NULL, NULL, NULL, $query_array, false,$null);
To do what you want you could do two things:
1) Combine your $conditions arrays and let CakePHP build your new query so you can simply use $this->Model->find() again.
2) Use this. It's an expansion for the mysql datasource that adds the option to do $this->Model->find('sql', array('conditions' => $conditions)) which will return the SQL-query. This option might cause trouble, because for some find calls (especially when you're fetching associated models) CakePHP uses multiple queryies to fetch the associated models (especially in case of hasMany-associations).
If at all possible, option 1 will probably cause the least trouble. Another problem with going with 2 is that if you're trying to combine two queries with conflicting conditions (like 'name = Hansel' in query 1 and 'name = Gretel' in query 2) you will just find nothing unless you plan on writing extra code to parse the resulting queries and look for conflicts..
Going with 1 will probably be a lot simpler and will probably avoid lots of problems.

Custom CakePHP order by clause for jQuery autocomplete

I have a database of locations the user can select from by typing and autocompletion. In my CakePHP controller, I do this:
$locations = $this->Location->find('all', array(
'conditions' => array('Location.name like' => '%'.$term.'%'),
'fields' => array('Location.id', 'Location.name', 'Region.name'),
'order' => array(
array('Location.name = "'.mysql_real_escape_string($term).'"'
=> 'desc'),
'Location.name'
),
'limit' => 10,
'recursive' => 1,
));
It works perfectly fine, but it feels like a hack, and I'd rather not escape SQL literals myself.
The first order by clause is needed since a perfect match might otherwise not make it to the top of the alphabetically sorted list.
I considered moving the equality-test into a virtual field, but I don't feel it's a very elegant solution when the $term is dynamic.
How do I implement this in a better way?
As far as the structure of your query is written this is fine.
In regards to having to escape SQL yourself, this is from the Cookbook:
CakePHP already protects you against
SQL Injection if you use CakePHP's ORM
methods (such as find() and save())
and proper array notation (ie.
array('field' => $value)) instead of
raw SQL. For sanitization against XSS
its generally better to save raw HTML
in database without modification and
sanitize at the time of
output/display.

Categories