using LIKE with ZEND_DB - zend-framework

I want to use a query which uses LIKE .. for e.g select * from xxxx where zzzz LIKE 'a%';
How can I do that using Zend DB?
I have already tried something like $db->query('SELECT * FROM XXXX where zzzzz LIKE ?','\'' . $query .'%\''); but it is not working.
Thanks

You're double quoting. You don't need the escaped quotes around $query. Prepared statements will take care of that for you:
$db->query('SELECT * FROM XXXX where zzzzz LIKE ?', '%' . $query .'%');

$user = new Application_Model_DbTable_User();
$uname=$_POST['uname'];
$query = $user->select()->where('firstname LIKE ?', $uname.'%')->ORwhere('lastname LIKE ?', $_POST['lname'].'%')->ORwhere('emailid LIKE ?', $_POST['email'].'%');
$userlist = $user->fetchAll($query);

Related

powershell - get a keyword from query string

I'm learning PowerShell scripting & want to extract tableName from SQL Query String. For example, I've this query -
$q = "SELECT * FROM [TestDB].[dbo].Invoice_Details where Clientname='ABC'"
where I want to extract table name i.e. it should output this - Invoice_Details
Currently, I'm doing this with following working code -
$q1 = $q -split '\[dbo\]\.'
$q2 = $q1[1] -split ' where '
write-host $q2[0] #here I get it right (Invoice_Details)
But, sometimes the query may/ may not have bracketed names like - [TestDB].[dbo].
So, I want to optimize this code so that it will work even if query containing any combination of bracketed/ bracketless tableNames
Try something like this:
$res = ([regex]'(?is)\b(?:from|into|update)\s+(\[?.+\]?\.)?\[?(\[?\w+)\]?').Matches($q)
write-host $res[0].Groups[2].Value

Modifying Columns In Zend Framework Select

In a Zend_Db_Select object, I am doing a join to get user information for some data records. For the join is on a userId, I would like to combine the user first and last name into a single column of name.
Basically I am looking to have something similar to this:
$table = array('u' => 'User');
$condition = 'u.id = t.id';
$columns = array('UserName' => 'u.FirstName + " " + u.LastName')
$select->joinLeft($table, $condition, $columns);
I have tried using a Zend_Db_Expr with no luck and the above does not work.
How would I go about doing this?
Zend_Db_Expr is the way to go, but you'll have better luck if you use the database's concatenation function. Assuming MySQL:
$columns = new Zend_Db_Expr("CONCAT(u.FirstName, ' ', u.LastName') AS name")

How to write Zend db select with OR condition inside AND condition

Can someone guide me to write a query like below using Zend db select :
SELECT `tbl_md_users`.*
FROM `tbl_md_users`
WHERE
user_type <> 'TYPE1')
AND (first_name LIKE '%tom%' OR last_name LIKE '%tom%' OR user_name LIKE '%tom%')
If you wanted
SELECT `tbl_md_users`.*
FROM `tbl_md_users`
WHERE
user_type <> 'TYPE1')
AND (first_name LIKE '%tom%' OR first_name LIKE '%dick%' OR first_name LIKE '%harry%')
then the first answer doesn't work
I used Zend_Db_Expr instead
$likeTom = new Zend_Db_Expr("first_name LIKE '%tom%'");
$likeDick = new Zend_Db_Expr("first_name LIKE '%dick%'");
$likeHarry = new Zend_Db_Expr("first_name LIKE '%harry%'");
$query = $database->select ()
->from ('tbl_md_users')
->where ('user_type <> ?', 'TYPE1')
->where ("{$likeTom} OR {$likeDick} OR {$likeHarry}");
$query = $database->select ()
->from ('tbl_md_users')
->where ('user_type <> ?', 'TYPE1')
->where ("first_name LIKE '%?%' OR last_name LIKE '%?%' OR user_name LIKE '%?%'", 'tom');
The current, up-to-date solution is to call nest() and unnest() in the where clause:
$select->where
->nest()
->equalTo('column1', 1)
->or
->equalTo('column2', 2)
->unnest()
->and
->equalTo('column3', 3);
I think there is no way to use Zend_Db_Select for this. You could use
$this->table->getAdapter()->quoteInto()
To write an custom query.

SphinxQL and SPH_MATCH_ANY

I am using SphinxQL to query Sphinxsearch engine. I want to simulate the SPH_MATCH_ANY which is implemented in the php API like this :
$cl->SetMatchMode(SPH_MATCH_ANY);
$cl->Query("test query", "index");
=> search for docs matching with "test" OR "query"
So, I have written a function (php) to replace spaces and other special chars with pipes (|) in order to use it with SphinxQL :
function formatQuery($str) {
return trim(preg_replace('/[^-_\'a-z0-9]+/', '|', $str), ' |');
}
$str = "test query";
$sql = "SELECT * FROM index WHERE MATCH('" . addslashes(formatQuery($str)) . "')";
=> SELECT * FROM index WHERE MATCH('test|query');
The problem is, for some characters like - (minus), it can break the query, example :
$str = "i-phone is great";
$sql = "SELECT * FROM index WHERE MATCH('" . addslashes(formatQuery($str)) . "')";
=> SELECT * FROM index WHERE MATCH('i-phone|is|great')
=> ok
$str = "i - phone is great";
$sql = "SELECT * FROM index WHERE MATCH('" . addslashes(formatQuery($str)) . "')";
=> SELECT * FROM index WHERE MATCH('i|-|phone|is|great')
=> broken query because of "|-|"
Do you know a better way to make SphinxQL queries work in SPH_MATCH_ANY mode? or a better regexp to make it works for all cases?
I know I could use a more restrictive regexp like this:
preg_replace('/[^a-z0-9]+/', '|', $str)
but it would split strings like "i-phone is great" in 'i|phone|is|great' and I don't want that...
Thank you,
Nico
One way might be to use quorom
$sql = "SELECT * FROM index WHERE MATCH('\"" . addslashes($str) . "\"/1')";
you will need to add - to your charset_table tho, so it becomes part of a word.
The other option is
$query = preg_replace('/(\w+?)[-\'](\w+?)/','$1~$2',$query);
$query = preg_replace('/[^\w\~]+/','|',$query);
$query = preg_replace('/(\w+~\w[\w~]*)/e','"\"".str_replace("~"," ","$1")."\""',$query);
To turn it into a phrase.

[zend][db] fetchAll with multiple variables

I'm trying to use fetchAll on a query that has 2 variables. I can't figure out the syntax.
I can manage with only 1 variable:
$sql = "SELECT * FROM mytable WHERE field1 = ?";
$this->_db->fetchAll($sql,$value1); # that works
However I'm having some issues when query has multiple variables
$sql = "SELECT * FROM mytable WHERE field1 = ? AND field2 = ?";
$this->_db->fetchAll($sql,$value1,$value2); # doesn't work
$this->_db->fetchAll($sql,array("field1"=>$value1,"field2"=>$value2)); # doesn't work either
The reason why I want to use ? instead of placing the variables directly into the query is that I've learned that using ? allows for the query to be compiled generically by the db engine and improves performances.
There are two types of parameter, named parameters and positional parameters. You're mixing the two types and that won't work.
Named parameters match a placeholder by name. Names are started with the : symbol. The parameter names are not the same as the names of the columns you happen to use them for. You supply parameter values in an associative array, using the parameter name (not the column name) as the array keys. For example:
$sql = "SELECT * FROM mytable WHERE field1 = :param1 AND field2 = :param2";
$this->_db->fetchAll($sql,array("param1"=>$value1,"param2"=>$value2));
Positional parameters use the ? symbol for the placeholder. You supply parameter values using a simple (non-associative) array, and the order of values in the array must match the order of parameter placeholders in your query. For example:
$sql = "SELECT * FROM mytable WHERE field1 = ? AND field2 = ?";
$this->_db->fetchAll($sql,array($value1,$value2));
Most brands of SQL database natively support only one style or the other, but PDO attempts to support both, by rewriting the SQL if necessary before preparing the query. Since Zend_Db is modeled after PDO, Zend_Db also supports both parameter styles.
This question is a bit old, but I thought I'd just add to it for reference sake.
I would recommend starting to use Zend_Db_Select with Zend_Db. I've been doing a lot with Zend_Db lately. More from Zend_Db_Select reference guide.
Lets assume you have a Zend_Db adapter: $this->_db
# this will get the Zend_Db_Select object
$select = $this->_db->select();
# now you build up your query with Zend_Db_Select functions
$select->from('mytable');
$select->where('field1 = ?', $field1);
$select->where('field2 = ?', $field2);
[...]
# echo to see the SQL (helps in debugging)
# SELECT * FROM mytable WHERE field1 = ? AND field2 = ? [...]
echo '<p>My SQL: ' . $select . '</p>';
# Execute the SQL / Fetch results
$results = $select->query()->fetchAll();
That's the basics from your given example, but the Zend Framework reference guide on the select object has a lot of good information on how to build even more complex queries with JOINS, UNIONS, GROUP BY, LIMIT, HAVING, etc.
If you wanted to use an alias name for a table or parameters, you use an associative array with the alias name being the index value:
# SELECT p.* FROM products AS p
$select->from('p' => 'products');
If you want to return only selected fields, you add an array of field names as a second parameter:
# SELECT model FROM products
$select->from(products, array(model));
Actually, the above could should produce fully qualified SQL as:
SELECT 'products'.model FROM 'products'
but I wrote the above for brevity and clarity in the example.
One thing I just came across is using AND and OR in the WHERE condition.
# WHERE a = $a
$select->where('a = ?', $a);
# WHERE a = $a AND b = $b
$select->where('a = ?', $a);
$select->where('b = ?', $b);
# WHERE a = $a OR b = $b
$select->where('a = ?', $a);
$select->orWhere('b = ?', $b);
# WHERE a = $a AND b = $b
$select->orWhere('a = ?', $a);
$select->where('b = ?', $b);
Notice, that whatever the following "where" function you use, will combine with the previous statement as that operand. Ok, that sounded confusing.
If the second "where" is an "OR" it will be an "OR" conditional. If the second "where" is a "AND" the statement will be "AND".
In other words, the first WHERE function is ignored in terms of what condition it will use.
In fact, I just asked a question on Stack Overflow yesterday regarding doing a complex WHERE using select.
Hope that helps!
Cheers!
Try this:
$sql = "SELECT * FROM mytable WHERE field1 = ? AND field2 = ?";
$statement = $this->_db->query($sql,array("field1"=>$value1,"field2"=>$value2));
$data = $statement->fetchAll();
$this->_db must be an instance of Db adapter.
Heres the actual Zend way to code for this.
$sql = "SELECT * FROM mytable WHERE field1 = :param1 AND field2 = :param2";
$this->_db->fetchAll($sql,array("param1"=>$value1,"param2"=>$value2));
$where = $this->_db->select()
->from('mytable')
->where('field1 = ?',$value1)
->where('field2 = ?',$value2);
$rowSet = $this->_db->fetchAll($where);
This works great for me