My goal is to search column A for string B and if it is found, return which row it was found in, and if it wasn't found, I would need to know that as well in order to take a different course of action.
My current PHP code:
$string = "teststring";
$searchquery = "SELECT *
FROM AllStringsTable
WHERE `Column_A` LIKE '$string'"
$searchresult = mysql_query($searchquery) or die(mysql_error());
$row = mysql_fetch_row($searchresult);
echo "The returned row was: $row";
This just breaks and does nothing, so I think I'm way off here. Also, I have read that for exact string searching that doesn't require wildcard substrings, etc, LIKE is not needed. So I'm not sure what I would use instead...
You're almost there. You need the %
wildcards:
// First, prevent sql injection with mysql_real_escape_string
$string = mysql_real_escape_string($string);
$searchquery = "SELECT * FROM AllStringsTable WHERE `Column_A` LIKE '%{$string}%'";
// ----------------------------------------------------------------^^^-------^^^
$searchresult = mysql_query($searchquery) or die(mysql_error());
if (mysql_num_rows($searchresult) == 0) {
echo "no rows found";
}
else {
// You need to loop over the result resource to get all the rows.
// Better to use mysql_fetch_array()
while ($row = mysql_fetch_array($searchresult)) {
$print_r $row;
}
If you want to do an exact match, use = instead of LIKE:
SELECT ... WHERE Column_A = '$string';
If you want to do a substring match (which I suspect is more what you want), use LIKE with the % wildcards:
SELECT ... WHERE Column_A = '%$string%';
The difference is that the first query requires that the entire Column_A matches exactly. The second query requires only that the exact word is found somewhere in the column.