SQL LIKE with% query for text in Perl
I have the following piece of code:
$query = "SELECT tac FROM lte_modems WHERE tac = ?";
$check_name = $dbh->prepare($query);
$my_name = "Jo"
$check_name->execute($my_name);
my @result = $check_name->fetchrow_array();
which works great. I would like to modify the SQL query to return names starting with "Jo": i.e. my SQL query should be
$query = "SELECT tac FROM lte_modems WHERE tac LIKE '?%'";
but it doesn't work. any help pls? maybe i need to escape some characters?
early
source to share
You need to include %
in your parameter. Otherwise, you will get extra quotes as DBI descriptors for you.
my $sth = $dbh->prepare( "SELECT tac FROM lte_modems WHERE tac LIKE ?" );
$sth->execute( $my_name . '%' );
The trick really always allows DBI to do all the quotes and do nothing by itself. DBI doesn't care if the placeholder comes ?
after the equals =
, a LIKE
or REGEXP
or whatever. This speeds up quotes and adds quotes as needed. You don't want to get involved in this.
source to share