Lon*_*rim 5 php arrays perl mysqli parameter-passing
我正在撞墙,因为我习惯在Perl中做事的方式在PHP中不起作用.这很可能是基本的,我不知道如何正确地提出这个问题.症结:我习惯在列表上下文中发送一个数组作为Perl中函数的参数,但在PHP中我只传递对数组的引用.
我正在尝试使用MySQLi在PHP中进行基本的SQL查询,例如SELECT * FROM my_table WHERE first_name = 'Bob' AND last_name = 'Smith' AND city = 'Akron'
.诀窍是,我的代码事先不知道查询中的术语.查询是根据用户想要使用的搜索项而动态形成的.在Perl中这很容易.在PHP中,我不知道该怎么做.问另一种方式:如何动态形成并传递PHP中的值列表?
我以前在Perl中做的事情:
my %terms = (
'first_name' => 'Bob',
'last_name' => 'Smith',
'city' => 'Akron'
);
my @keys = keys %terms;
my $where_string = join(' AND ', map("$_ = ?", @keys));
my @values = @terms{@keys};
my $sql = "SELECT * FROM my_table WHERE $where_string";
# Should give me 'SELECT * FROM my_table WHERE first_name = ? AND last_name = ? AND city = ?'
my $sth = $dbh->prepare($sql);
$sth->execute(@values);
Run Code Online (Sandbox Code Playgroud)
我想在PHP中尝试做什么不起作用:
foreach ($terms as $key => $value) {
$keys[] = "$key = ?";
$values[] = $value;
$types .= (is_numeric($value) ? "i" : "s");
}
$where_string = implode(' AND ', $keys);
$sql = "SELECT * FROM my_table WHERE $where_string";
$sth = $dbh->prepare($sql);
$sth->bind_param($types, $values); # Only I need to pass @values,
# the list of the elements of the array,
# not a reference to the array
$result = $sth->execute();
Run Code Online (Sandbox Code Playgroud)
这可能是我的大脑如此Perl-addled我忘记了所有的常识.
你可能想要的是call_user_func_array()
:
$args = array_merge( array( $types ), $refs_to_values );
call_user_func_array( array( $sth, 'bind_param' ), $args );
Run Code Online (Sandbox Code Playgroud)
是的,它有点难看; 有时Perl的灵活性是一个优势.
归档时间: |
|
查看次数: |
201 次 |
最近记录: |