且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Codeigniter 2.0中编写SQL查询

更新时间:2022-11-28 08:48:30

可能是:

  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'];另一件事:如果你想传递'som​​ething'作为一个变量,你可以将一个变量传递给另一个变量,例如:
}



可以使用参数化查询,如

  $ 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.