所以我有这个功能来搜索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 是用户启动的搜索,并从网址(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语法错误:
错误号码:1064
您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在第2行'WHERE
firstname
LIKE'%paul%'或lastname
LIKE'%paul%'附近使用正确的语法SELECT * WHERE
firstname
LIKE'%paul%'或lastname
LIKE'%paul%'文件名:/www/htdocs/w00a94ee/c/controllers/contributors.php
行号:23
在这两种情况下,函数都会得到完全相同的字符串paul
,为什么它不起作用?
//修改
function __construct()
{
parent::__construct();
$this->load->database('databasename');
$this->db->from('tablename');
}
答案 0 :(得分:3)
您忘了指定要选择的表格FROM
。
$this->db->from('tablename');
编辑:问题是你在构造函数中添加from
,然后你正在调用:
$this->db->where('slug', $slug);
$result = $this->db->get();
在调用SearchContributors
之前。这将运行查询并重置变量。
因此,当您致电SearchContributors
时,不再设置FROM
。
您需要将$this->db->from('tablename');
置于SearchContributors
内,而不是构造函数。通常一个好主意是使模型函数自包含,而不需要外部函数(例如__construct
来调用它们)。
答案 1 :(得分:0)
你缺少get('table_name');
if (count($search_pieces) == 1 )
{
$this->db->like('firstname', $search);
$this->db->or_like('lastname', $search);
$result = $this->db->get('Your_tablename'); //-->>Here you can go
}
查看错误
select * WHERE......
但是哪里是“从表WHERE”...... ??我认为这是我亲爱的问题
您也可以在这里更改
$this->db->where('slug', $slug);
$result = $this->db->get('My_Table');