我正在为一个问题苦苦挣扎,因为我习惯在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);
我正在尝试使用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();
也许是因为我的大脑被Perl日用成了马蜂窝,以至于我忘记了常识。