当前位置: 动力学知识库 > 问答 > 编程问答 >

php - How to check if string exists in table which is added using addslashes?

问题描述:

I am storing names in a database-column called 'name' using the following function:

public function insertCategory($arrCat) {

$id = $this->insert($arrCat);

return $id;

}

$arrCat is passed from my controller:

$arrCat = array(

'name' => addslashes($name),

'type' => $type,

'rank' => $catOrder,

'created_by' => $created_by,

'created' => Zend_Date::now()->toString('yyyy:MM:dd HH:mm:ss'),

'active' => 'y',

'app_id' => $appId

);

This code inserts data properly. But I want 'name' to be unique values so I have written a function checkNameExists($name, $created_by, $app_id):

public function checkNameExists($name,$created_by,$app_id) {

$sql= $this->_db->select("name")

->from("titles")

->where("name LIKE '" . addslashes($name) . "' AND created_by='" . $created_by . "' AND app_id = '".$app_id."' ");

//Tried with this query as well

//$sql="select name from titles where name = '$name' AND created_by=$created_by AND app_id=$app_id";

$result = $this->_db->fetchAll($sql);

if(count($result) > 0){

return 1;

} else {

return 0;

}

}

So depending on the value returned by checkNameExists() I want to perform an insert or return a 'Name already exists'-message to the user. But the function checkNameExists is always returning 0 even if the same name exists in my table.

I am using Zend Framework 1 and MySQL.

网友答案:

Zend_Db_Select has a nice fluent interface to it. First thing you need to do is use its prepared statements a bit better:

$sql = $this->_db->select()
    ->from('titles', array('name'))
    ->where('name       = ?', $name)
    ->where('created_by = ?', $created_by)
    ->where('app_id     = ?', $app_id);

This will help with the SQL injection issue. Because Zend_Db uses prepared statements when inserting, you don't need to use addslashes, just pass it in raw. This will simplify getting it out of the db because you then don't need to stripslashes. Also, because you are comparing un-slashed strings, all you need is the = operator as LIKE is only effective if you use a % as a wildcard.

网友答案:

You should not use addslashes or equivalent in some array or variable but only when you are building a String query.

Moreover you should use the specific function for your database for example (https://php.net/manual/en/mysqli.real-escape-string.php for mysql).

Finally i think you are querying your database for three parameters ($name, $created_by,$app_id) and the function checkNameExists will send you 1 if the three are true, can you verify if the value of the three parameters?

分享给朋友:
您可能感兴趣的文章:
随机阅读: