在Codeigniter 2.0中编写SQL查询 [英] Writing SQL Queries in Codeigniter 2.0
问题描述
我有以下功能,不工作,我有最难的时间试图找出来。我12岁,只是学习,请原谅我:
function get_answer(){
$ answer = $ this - > db-> query(SELECT COUNT(questions)FROM possible_quest WHERE questions ='something');
return $ answer;
}
当我在phpmyadmin中运行以下SQL查询时,它返回预期结果
SELECT COUNT(questions)FROM possible_quest WHERE questions ='something'
如何使用上面的函数在CodeIgniter中工作?
我得到的PHP错误是
遇到PHP错误
严重性:4096
消息:CI_DB_mysql_result类的对象不转换为字符串
可能是:
function get_answer()
{
$ query = $ this-> db-> query(SELECT COUNT FROM possible_quest WHERE questions ='something');
$ count = $ query-> row(); //返回第一行的对象
return $ count-> count;
// OR
$ count = $ query-> row_array(); // return a asociative array of the result
return $ count ['count'];另一件事:如果你想传递'something'作为一个变量,你可以将一个变量传递给另一个变量,例如:
}
可以使用参数化查询,如
$ sql =SELECT COUNT(questions)AS count FROM possible_quest WHERE questions =?
$ query = $ this-> db-> query($ sql,array($ something));
这有利于自动转义你的变量,所以你不必担心sql注入。 / p>
I have the following function that does not work and I'm having the hardest time trying to figure it out. I'm 12 and just learning, so forgive me:
function get_answer() {
$answer = $this->db->query("SELECT COUNT(questions) FROM possible_quest WHERE questions='something'");
return $answer;
}
When I run the following SQL query in phpmyadmin, it returns the expected result
SELECT COUNT(questions) FROM possible_quest WHERE questions='something'
How do I get this working in CodeIgniter using my function above?
The PHP error I get is
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysql_result could not be converted to string
Could be:
function get_answer()
{
$query = $this->db->query("SELECT COUNT(questions) AS count FROM possible_quest WHERE questions='something'");
$count = $query->row(); // returns an object of the first row
return $count->count;
// OR
$count = $query->row_array(); // returns an asociative array of the result
return $count['count'];
}
Another thing: if you want to pass 'something' as a variable, you can use parametrized query, like
$sql = "SELECT COUNT(questions) AS count FROM possible_quest WHERE questions = ?";
$query = $this->db->query($sql, array($something));
which has the benefit of escaping automatically your variable, so you don't worry about sql injections.
这篇关于在Codeigniter 2.0中编写SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!