我想通过使用QueryBuilder.php中的$furniture1
方法将Product类的实例(例如save();
)保存到数据库。有没有办法将对象传递给它?
是否有可能或有更好的方法吗?
QueryBuilder.php
class QueryBuilder {
/**
* @var PDO $pdo
*/
protected $pdo;
/**
* Create a new query instance
*
* @param PDO $pdo
*/
public function __construct($pdo) {
$this->pdo = $pdo;
}
/**
* Save object to database
*/
public function save($obj, $table) {
// gets an associative array
$variables = get_object_vars($obj);
// arrays
$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
try {
$sql = "INSERT INTO " . $table . " (" . $columnString . ") VALUES (" . $placeholderString . ")";
$query = $this->pdo->prepare($sql);
$query->execute($bindings);
} catch(PDOException $e) {
return $e;
}
}
}
对象属性的var_dump:
array (size=6)
'material' => string 'wood' (length=4)
'id' => null
'type' => string 'Furniture' (length=9)
'title' => string 'Desk' (length=4)
'price' => float 199.99
'size' => string '200x100x100 cm' (length=14)
修改
var_dump($variables);
,
var_dump($columnString);
,
var_dump($placeholderString);
返回:
QueryBuilder.php:81:
array (size=0)
empty
QueryBuilder.php:82:string '' (length=0)
QueryBuilder.php:83:string '' (length=0)