I need a little help with my code here. So far, when I go to the page, whole view is seen. When I set search and POST it, it works too. But when I add –> 2 or more <– keywords, i get an error. So the problem is in the forearch loop else construction.
In that case I get this error:
query fout 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 ‘ORDER BY custsurname, custforename, custmidname’ at line 6
I tried many ways of constructing, but somehow doesnt seem to work.
My code is below:
if(isset($_POST['search']))
{
$search = $_POST['search'];
$terms = explode(" ", $search);
$customerlistquery = "
SELECT *
FROM customer
LEFT JOIN company
ON customer.compid=company.compid
WHERE
";
foreach ($terms as $each)
{
$i++;
if ($i == 1)
{
$customerlistquery .= "concat(custsurname, custforename, custmidname) LIKE '%$each%' ORDER BY custsurname, custforename, custmidname";
}
else
{
$customerlistquery .= "OR concat(custsurname, custforename, custmidname) LIKE '%$each%' ORDER BY custsurname, custforename, custmidname";
}
}
}
else
{
$customerlistquery = "
SELECT *
FROM customer
LEFT JOIN company
ON customer.compid=company.compid
ORDER BY custsurname, custforename, custmidname
";
}
And just one last more question. Why is PHP whining about undefined variable: i?
Notice: Undefined variable: i in ...
Is this a standard message at every “throwaway variable”?
@newfurniturey is right, the first time you use
$i, is here:$i++;Basically, your adding1to something that doesn’t exist:$ihasn’t been declared, so there’s no value to which you can add 1.Yes, you could just turn the notices off, just hiding them. Your logs, however will get cluttered very quickly. It’s therefore good practice to write your code in such a way so that it runs under
E_STRICT | E_ALLsettings without any warnings or notices.After you’ve addressed this issue, I can tell you now that you’ll see SQL syntax errors all over the place, too:
Each bit of query you concatenate ends in an ORDER BY clause. SQL won’t accept query’s that look like
So I’d suggest you concat the
ORDER BYclause after the loop:Once you get this query to run, don’t be surprised if its dead slow: The top 3 things to slow query’s right down are:
LIKEwith wildcardsORclausesIf your query has 2 of these three characteristics, there’s a 99% chance that SQL will perform a full table scan and write a temp table to disk. Far from ideal, then.