从数组绑定值? [英] Binding values from arrays?

查看:65
本文介绍了从数组绑定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这种不完整的方法将对象保存在数据库中:

So I have this incomplete method to save object in database:

public function save() {
    $variables = get_object_vars($this);
    $attributes = [];

    foreach ($variables as $variable => $value) {
        $attributes[] = $value;
    }

    $variableString = implode(", ", $attributes);

    foreach ($variables as $variable => $value) {
        $attributes[] = ":" . $value;
    }

    $valueString = implode(", ", $attributes);

    $sql = "INSERT INTO products (" . $variableString . ") VALUES (" . $valueString . ")";
    $query = $this->pdo->prepare($sql);
    // ...
}

如何使用已经创建的数组绑定这样的值?

How do I bind values like this using arrays I already created?

$query->execute(array(
  ':username' => $username,
  ':email' => $email,
  ':password' => $password
));

推荐答案

这就是我要这样做的方式:

This is how I would do it:

// This gets an associative array
$variables = get_object_vars($this);

// Init
$columns = [];
$placeholders = [];
$bindings = [];

// Loop through variables and build arrays
foreach ($variables as $column => $value) 
{
   $columns[] = $column;
   $placeholder = ':' . $column;
   $placeholders[] = $placeholder;
   $bindings[$placeholder] = $value;
}

// Create strings
$columnString = implode(',', $columns);
$placeholderString = implode(',', $placeholders);

// Prepare query
$sql = "INSERT INTO products (" . $columnString . ") VALUES (" . $placeholderString . ")";
$query = $this->pdo->prepare($sql);

// Execute query
$query->execute($bindings);

基本上,您需要先准备好所需的作品,然后再将它们传递出去.

You basically prepare the pieces you need upfront and then pass them through.

我应该提到这可能是一种脆弱的方法,因为它假定您的类的属性在数据库表中始终为 .基本上,只需一个$myModel->non_column = 123;语句即可推入并中断查询.

I should mention this may be a brittle way of doing this due to the fact that it assumes the attributes on your class are always in your database table. It basically takes one $myModel->non_column = 123; statement somewhere where to push through and break your query.

似乎您正在尝试构建自己的Active Record实现?可能想看看一些大型企业是如何做到这一点的,或者只是使用他们的企业.

Seems like you are trying to build your own Active Record implementation perhaps? May want to look at how some of the big players do this, or just use theirs.

这篇关于从数组绑定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆