php - 想要在 PHP 中传递值列表(如在 Perl 中),而不是对数组的引用

标签 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);

我在 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 弄糊涂了,以至于我忘记了所有的常识。

最佳答案

您可能想要的是 call_user_func_array() :

$args = array_merge( array( $types ), $refs_to_values );
call_user_func_array( array( $sth, 'bind_param' ), $args );

是的,有点丑;有时 Perl 的灵 active 是一种优势。

关于php - 想要在 PHP 中传递值列表(如在 Perl 中),而不是对数组的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21147277/

相关文章:

php - 使用 PHP 内置 ltrim() 删除单个字符

javascript - 推送数组中的值以匹配特定格式

javascript - 在 .slice 之后重置 JSON 数组

perl - Moo 的 MooseX::NonMoose 等价物是什么?

perl - 从Perl中的套接字读取特定数量的字节

PHP,计算自添加以来的时间

php - 从 mysql 检索数据

perl - 如何增加 dotcloud 上 HTTP GET 请求的允许大小?

php - Eloquent Laravel 模型上的 __construct

c++ - 如何在 C++ 中使用指针翻转 Char 数组