So I have this function to search entries in a MySQL database:
<?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;
}
?>
I use the function on two occasions.
Case A is a user initiated search and gets the search query from the URL (domain.com/contributors/?x=paul). This works fine.
<?php
if (isset($_GET['x']))
{
$x = $_GET['x'];
$result = $this->SearchContributors($x);
}
?>
Case B is a backup for when a user enters an invalid slug name (domain.com/contributors/paul instead of domain.com/contributors/pauline-surname) and gets the search query directly:
<?php
$this->db->where('slug', $slug);
$result = $this->db->get();
if ($result->num_rows() == 0)
{
$x = str_replace('-', ' ', $slug);
$result = $this->SearchContributors($x);
}
?>
This returned an MySQL syntax error:
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
firstnameLIKE ‘%paul%’ ORlastnameLIKE ‘%paul%” at line 2SELECT * WHERE
firstnameLIKE ‘%paul%’ ORlastnameLIKE ‘%paul%’Filename: /www/htdocs/w00a94ee/c/controllers/contributors.php
Line Number: 23
The function gets the very same string paul in both cases, so why doesn’t it work?
//EDIT
function __construct()
{
parent::__construct();
$this->load->database('databasename');
$this->db->from('tablename');
}
You forgot to specify which table you want to select
FROM.EDIT: The problem is you are adding the
fromin your constructor, then you are calling:before calling
SearchContributors. This runs the query and resets the variables.So, when you call
SearchContributors,FROMis no longer set.You need to put
$this->db->from('tablename');insideSearchContributorsand not the constructor. It’s usually a good idea to make model functions self-contained, and not require outside functions (such as__constructto call them).