i have declared my variables in the starting of code.
require_once("connection.php");
$tag2[0] = '';
$tag2[1] = '';
$tag2[2] = '';
$tag2 = trim('samsung');
$tag2 = explode(' ', $tag2);
$sql="
SELECT name FROM producttable WHERE name LIKE '%$tag2[0]%' AND name LIKE '%$tag2[1]%' and name LIKE '%$tag2[2]%'";
But still i am getting undefined offset error
Notice: Undefined offset: 1 in E:\xampp\htdocs\und.php on line 8
Notice: Undefined offset: 2 in E:\xampp\htdocs\und.php on line 8
i have read that we should declare variables in the starting to avoid these types of errors.
so now none of your array elements exist. Then you create an array again from the explode() function
$tag2 = explode(' ', $tag2);
but because the thing it’s exploding only contained the word “Samsung”, it only has a single element (element zero) and hence you get errors for elements one and two.
i was just trying to get declare the array values to avoid the undefined warnings for below sql
$sql="
SELECT name FROM producttable WHERE name LIKE '%$tag2[0]%' AND name LIKE '%$tag2[1]%' and name LIKE '%$tag2[2]%'";
But i dont know if the user will enter 1 word or 3 words.
so i was trying to declare the array values inside foreach loop.
But the problem is if user will enter only 1 word “samsung”
then the foreach loop will also echo only one value and i will be able to declare only 1 value.
if rest 2 remain undeclare then i will again get undefined index warning.
As you can see there are 3 array values needed for the sql.
so what is the solution that can declare 3 array values whether value is null or not null.
You need to validate what the user types in, split it into individual words, then add each one to your query as you need to. Don’t have a query where you have three LIKE values and then have to fudge it to work when the user only types in one or two, just have the query only add a LIKE clause when it has another selection to work with.
$words = explode(' ', $whatever-the-user-typed-in-after-validation);
if (count($words) > 0) {
$query = "SELECT name from producttable where name ";
foreach ($words as $word) {
// add the next LIKE clause on here
}
// execute the query
}