Fat Free Framework PHP Sql statement with in expression

这一生的挚爱 提交于 2020-03-03 07:50:28

问题


I'm trying to include a list of strings to be used in an "in" expression in a sql statement for example:

select * from poop where id in ('asd','sas','ser')

I want to pass the in parameter from a variable. The quoting is really screwing me up. Should I be passing this as a string which I have been trying to no avail by making a comma seperated string that looks like this:

282366381A,240506808A,244154247A,491404349A,242443808B,328409296A,239723812A,383423679M

or "282366381A","240506808A","244154247A","491404349A","242443808B","328409296A"

or '282366381A','240506808A','244154247A','491404349A','242443808B','328409296A'

None of these work or is there a different way using an array of values?

This is the statement I'm using with the string:

$cernerResults = $this->cernerdb->exec( "select
        pat as HICN,
    from pat
    where
        HICN in ( ? )", $hicsString );

Edit:

I was able to get around this by constructing the entire query as a string like this:

$query = "select pat as HICN from pat where HICN in (".$hicsString.")";

$hicsString has single quotes around each item like so:

'282366381A','240506808A','244154247A','491404349A','242443808B','328409296A'

The problem is that providing the string to the exec would result in no results. When looking at the freetds log file the in expression values would be double quoted as a whole or each one would be double single quoted and if i used no quotes they would not be quoted at all.

All of these would make the statement return no results. I should also mention that this is a Sybase database.


回答1:


I think your problem may come from the fact that PDO parser needs to have one value per question mark so it is able to validate it. So your "hack" with one question mark which is assigned to more than one value is where it fails IMHO.

This is how I handle case like that:

$values = ['asd','sas','ser'];
$count = count($values);
$results = $db->exec(
    "select * from poop where id in ( ?".str_repeat(", ?", $count-1).")",
    $values
);

In general I would advice you using data mappers instead of running the queries on a DB object. It is easier to iterate through them and it is more secure.



来源:https://stackoverflow.com/questions/41172114/fat-free-framework-php-sql-statement-with-in-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!