因此,我具有此功能来搜索MySQL数据库中的条目:
<?php
private function SearchContributors($search)
{
$search_pieces = explode(' ', $search);
if (count($search_pieces) == 1 )
{
$this->db->like('firstname', $search);
$this->db->or_like('lastname', $search);
$result = $this->db->get(); //the line from the error message below
}
//Other stuff for 2 and more pieces
return $result;
}
?>
我有两次使用该功能.
案例A是用户发起的搜索,并从URL(domain.com/contributors/?x=paul)获取搜索查询.这很好.
<?php
if (isset($_GET['x']))
{
$x = $_GET['x'];
$result = $this->SearchContributors($x);
}
?>
情况B是用户输入无效的子弹名称(domain.com/contributors/paul代替domain.com/contributors/pauline-surname)并直接获取搜索查询时的备份:
<?php
$this->db->where('slug', $slug);
$result = $this->db->get();
if ($result->num_rows() == 0)
{
$x = str_replace('-', ' ', $slug);
$result = $this->SearchContributors($x);
}
?>
这返回了MySQL语法错误:
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘WHERE
firstname
LIKE ‘%paul%’ ORlastname
LIKE ‘%paul%” at line 2SELECT * WHERE
firstname
LIKE ‘%paul%’ ORlastname
LIKE ‘%paul%’Filename: /www/htdocs/w00a94ee/c/controllers/contributors.php
Line Number: 23
在这两种情况下,该函数都具有完全相同的字符串保罗,那么为什么它不起作用?
//编辑
function __construct()
{
parent::__construct();
$this->load->database('databasename');
$this->db->from('tablename');
}
解决方法:
您忘记了指定要从中选择哪个表.
$this->db->from('tablename');
编辑:问题是您在构造函数中添加from,然后您调用:
$this->db->where('slug', $slug);
$result = $this->db->get();
在致电SearchContributors之前.这将运行查询并重置变量.
因此,当您调用SearchContributors时,将不再设置FROM.
您需要将$this-> db-> from(‘tablename’);在SearchContributors而不是构造函数中.使模型函数自成一体,而不需要外部函数(例如__construct来调用它们)通常是一个好主意.