php - Use single quotes within a string for prepared statement -
i have condition in query need filter on first , last name in users table. variables set this:
$firstname = input::get('firstname'); $lastname = input::get('lastname'); $myparameters = array(); $filterfirst = "'%" . $firstname . "%'"; $filterlast = "'%" . $lastname . "%'";
my sql query being set (dynamically):
$sqlstring = "select t1.id,t1.first_name, t1.last_name, t2.function " . "from users t1 join user_details t2 " . "on t1.id = t2.user_id"; if($firstname && $lastname){ $sqlstring .= " lower(first_name) lower(?)" . " or lower(last_name) lower(?)"; $myparameters = [$filterfirst,$filterlast]; } else{ if($firstname){ $sqlstring .= " lower(first_name) lower(?)"; $myparameters = [$filterfirst]; } if($lastname){ $sqlstring .= " lower(last_name) lower(?)"; $myparameters = [$filterlast]; } }
my query being executed using laravel prepared statement:
$resultset = db::select($sqlstring,$myparameters);
i've logged values of important variables this:
log::info($sqlstring); log::info($myparameters); log::info('first name: ' . $filterfirst); log::info('last name: ' . $filterlast);
i'm seeing logged values this:
[2015-06-26 09:32:52] local.info: select t1.id,t1.first_name, t1.last_name, t2.function users t1 join user_details t2 on t1.id = t2.user_id lower(first_name) lower(?) or lower(last_name) lower(?) [2015-06-26 09:32:52] local.info: array ( 0 => '\'%jer%\'', 1 => '\'%can%\'', ) [2015-06-26 09:32:52] local.info: first name: '%jer%' [2015-06-26 09:32:52] local.info: last name: '%can%'
so values correct '%jer%' , '%can%' values need go query, when put them variables array turn '\'%jer%\'' , '\'%can%\'' sql command being executed isn't working correctly (returning nothing).
does have idea how can work around this? need array contain string single quote without adding single quotes or slashes need '%whateverigavein%'
edit: tried using key value array , named variables in sql statement doesn't make difference appearantly (as goes array turns '\'%whateverigavein%\''
you making mistake of adding quotes content of variable:
$firstname = "joe"; $filterfirst = "'%" . $firstname . "%'"; var_dump($filterfirst) //string(7) "'%joe%'" <-- notice quotes
to include needed %
string:
$filterfirst = "%{$firstname}%";
or
$filterfirst = "%" . $firstname . "%";
will both result in string(5) "%joe%"
Comments
Post a Comment