My question is fairly simple. I have a column in my table labeled 'area' that appears like:
ma_south-coast
ma_south-caost
ma_north
ca_los-angelos
ca_los-angelos
I want to be able to select just the 'ma' ones. I am trying to do something such as:
$res_area = mysqli_query($connection,"select area from users");
while ($row_state = mysqli_fetch_array($res_area)) {
$state_exp = reset(explode("_", $row_state['area']));
}
Printing $state_exp at this point would give me: mamamacaca which is good. But I want to filter so I only get the ma ones.
The optimal solution could be :-
$res_area = mysqli_query($connection,"select area from users WHERE area LIKE 'ma_*')";
while ($row_state = mysqli_fetch_array($res_area)) {
if(stripos(reset(explode("_", $row_state['area'])),'ma') !== FALSE)
{
$state_exp = reset(explode("_", $row_state['area']));
}
}
You can extend your query with WHERE column LIKE "ma%"
or check with substr($row_state['area],0,2)
if the first two characters are "ma".
You could try this:
$res_area = mysqli_query($connection,"select area from users");
while ($row_state = mysqli_fetch_array($res_area)) {
$state_exp = stristr(reset(explode("_", $row_state['area'])),'ma');
}
You're looking for the LIKE
operator. The LIKE
operator is used to search for a specified pattern in a column. Try this:
SELECT * FROM tablename WHERE areaLIKE 'ma_%';
You can read more about the LIKE
operator here.