[英]zend framework where statement in query
我如何使用php和zend framework在MySQL查詢中使用And / or。
$db=Zend_Db_Table::getDefaultAdapter();
$select=new Zend_Db_Select($db);
$select->from('users','*');
$select->joinInner('rest', 'users.repository = rest.id',array('username'));
$select->where('username='.$rest.' and sold=0');
return $db->fetchAll($select);
那是正確的方法嗎? 如果不是,正確的方法是什么?
您可以通過多次調用where()
將AND
添加到查詢中:
$select->where('this = ?', 'myValue')
->where('that = ?', 'myValue2');
這將轉換為:
... WHERE this = 'myValue' AND that = 'myValue2'
要將一個或多個OR
添加到查詢中,請使用orWhere()
:
$select->where('this = ?', 'myValue')
->orWhere('that = ?', 'myValue2');
這將轉換為:
... WHERE this = 'myValue' OR that = 'myValue2'
注意
一定要使用?
占位符語法,因為它是防止SQL注入的簡便方法。
那是一種方式,但是您應該使用? 變量的占位符,以防止SQL注入:
$select=new Zend_Db_Select($db);
$select->from('users','*');
$select->joinInner('rest', 'users.repository = rest.id', array('username'));
$select->where('username = ? and sold=0', $rest);
(如果有時也來自PHP變量,則對“出售”執行相同的操作。)
您還可以將具有多個where()
調用或orWhere()
where子句鏈接在一起orWhere()
如果需要),或者代替and:
$select=new Zend_Db_Select($db);
$select->from('users','*');
$select->joinInner('rest', 'users.repository = rest.id', array('username'));
$select->where('username = ?' $rest);
$select->where('sold = ?', 0);
由於Zend_Db_Select使用流利的影響力,因此您也可以這樣編寫:
$select=new Zend_Db_Select($db);
$select->from('users','*')
->joinInner('rest', 'users.repository = rest.id', array('username'))
->where('username = ?' $rest)
->where('sold = ?', 0);
以下內容將解決您的問題,請參閱帶有 WHERE'AND '子句的PHP postgres Zend Framework Select查詢,以更全面地了解where()和orWhere()的工作方式。
$db=Zend_Db_Table::getDefaultAdapter();
$select=new Zend_Db_Select($db);
$select->from('users','*');
$select->joinInner('rest', 'users.repository = rest.id',array('username'));
$select->where('username= ?',$rest);//multiple where() will use AND operator in query
$select->where('sold = ?', 0);//if you need the OR operator use the orWhere() method
return $db->fetchAll($select);
要回答問號(摘錄自手冊):
fetchAll($select, $value)//most of the Zend_Db methods follow this API
fetchAll()方法:此方法的第一個參數是包含SELECT語句的字符串。 或者,第一個參數可以是Zend_Db_Select類的對象。 適配器自動將此對象轉換為SELECT語句的字符串表示形式
即(?是$ value的占位符):
$select->where('id = ?', $id);
$select->orWhere('age > ?', $age);
您當前使用的是舊語法,但仍然可以使用,但已棄用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.