Issue
I'm trying to query my database to SELECT based on text input. If I manually type in the string, it queries correctly and returns the expected rows. However, if I use the variable that I stored the string in, it will not return any rows from my database. Can someone take a look at this code and share any ideas on the issue? I apologize, but I'm new to PHP and I'm just trying to get a simple review table to display properly.
I have a search input where the user types in a search in this format: "name, address, city, state". I used the explode() function to split the input into each component and named each $name, $address, $city, $state. I'm including the code where everything stops working.
$searchWords = explode(",", $text);
$address = $searchWords[1];
$name = $searchWords[0];
$city = $searchWords[2];
$state = $searchWords[3];
When I echo gettype() on each variable, the result is 'string' and the expected strings print to the screen. This is the code I am having issues with:
$display = mysqli_query($conn, "SELECT * FROM reviews WHERE address1 LIKE '%$address%'");
If I manually set $address = '123 Pokemon St' or any string and then use $address in the query, it works correctly. But if I try to use $address as it is after initially defining it, it will not work. I tried type-casting each value to a string but that did not work.
I know I may be able to find this information somewhere in PHP's documentation but I've already spent several hours searching through it to no avail. I need to finish my project today so any help is super appreciated :)
Solution
i think your problem is with whitespaces. since the format is
name, address, city, state
which will result in these values
// example of $text = "Donnie, Pokemon Street, Denver, Colorado"
$searchWords = explode(",", $text);
$address = $searchWords[1] // "Donnie";
$name = $searchWords[0]; // " Pokemon Street"
$city = $searchWords[2]; // " Denver"
$state = $searchWords[3]; // " Colorado"
can you try trimming the exploded values before passing it to the query?
$address = trim($searchWords[1]); // "Donnie"
$name = trim($searchWords[0]); // "Pokemon Street"
$city = trim($searchWords[2]); // "Denver"
$state = trim($searchWords[3]); // "Colorado"
hope this helps!
Answered By - Rangga Wiriaputra
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.