Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quote column names with Zend_Db?

I am using key as a column name in a MySQL table.

Since this is reserved, it needs to be escaped properly to be used in a query:

… WHERE `key` = 'test'

Manually this is no problem, but I am using the Zend Framework and want to have it handle the escape correctly, like this:

$table = new Application_Model_ATable();
$table->fetchRow ( $table->select()->where('key = ?','test') );

So the question is:

How to quote/escape column names with Zend_Db_Table?

like image 463
favo Avatar asked Jan 28 '12 09:01

favo


3 Answers

avoiding MySQL injections with the Zend_Db class

The guy explains it here actually but ill just pull out the quote quickly...

Any other part of that expression that needs to be quoted or delimited is your responsibility. E.g., if you interpolate any PHP variables into the expression, safety is your responsibility. If you have column names that are SQL keywords, you need to delimit them yourself with quoteIdentifier(). Example:

$select->where($db->quoteIdentifier('order').'=?', $myVariable)

Hope this helps!!

like image 130
Billy G Avatar answered Oct 09 '22 15:10

Billy G


try something like:

$table = new Application_Model_ATable();
$where = $table->getAdapter()->quoteInto('key = ?', 'test');
$table->fetchRow ( $where );

*--excerpt from Zend_Db_Table reference--*
Note The values and identifiers in the SQL expression are not quoted for you. If you have values or identifiers that require quoting, you are responsible for doing this. Use the quote(), quoteInto(), and quoteIdentifier() methods of the database adapter.

like image 22
RockyFord Avatar answered Oct 09 '22 16:10

RockyFord


One must quote column names when uppercase letters have been used. It is usefull to quote those names with $db->quoteIdentifier($columnName) when you plan to switch databese adapter in the future.

like image 27
Bartek Kosa Avatar answered Oct 09 '22 14:10

Bartek Kosa