简体   繁体   English

是否有与PDO :: FETCH_CLASS等效的INSERT或UPDATE?

[英]Is there an INSERT or UPDATE equivalent to PDO::FETCH_CLASS?

I have found the PDO::FETCH_CLASS very useful. 我发现PDO::FETCH_CLASS非常有用。 My classes map to tables. 我的班级映射到表格。 I just do a 我只是做一个

$query = $pdo->query("SELECT * FROM fixedTime WHERE
                  transmissionProgramID = '$transmissionProgramID'");
$query->setFetchMode(PDO::FETCH_CLASS, 'FixedTime');

and voila. 和瞧。

I would like to be able to do the reverse: ie instantiate an object load up the values to UPDATE or INSERT and once again voila. 我希望可以做相反的事情:即实例化一个对象,将值加载到UPDATE或INSERT,然后再次瞧瞧。

Have looked but cannot see if this is available. 看过但看不到是否可用。

Well, yes. 嗯,是。 To some extent you can use something similar for insert or update. 在某种程度上,您可以使用类似的内容进行插入或更新。

But to achieve that, you have to learn how to use PDO properly . 但是要实现这一点,您必须学习如何正确使用PDO So, first we have to fix your select code: 因此,首先我们必须修复您的选择代码:

$sql = "SELECT * FROM fixedTime WHERE transmissionProgramID = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$transmissionProgramID]);
$stmt->setFetchMode(PDO::FETCH_CLASS, 'FixedTime');
$ftime = $stmt->fetch();

See - we are using prepared statements here, that you should be always using anyway. 请参阅-我们在这里使用准备好的语句,无论如何您都应该一直使用。 And at the same time that's the key for the [semi-]automation we can use with updates. 同时,这是我们可以与更新一起使用的[半]自动化的关键。 Because with prepared statements you can use the object itself to provide values for the prepared query. 因为使用预准备语句,您可以使用对象本身为预准备查询提供值。

So, as long as you have object properties reflect table fields you can use a code like this: 因此,只要您具有对象属性来反映表字段,就可以使用如下代码:

$user = new stdClass();
$user->name = "foo";
$user->pass = "bar";

$sql = "INSERT INTO users VALUES (NULL, :name, :pass)";
$pdo->prepare($sql)->execute((array)$user);

But for the real automation you have to consider using an ORM , which is doing exactly what you're looking for. 但是对于真正的自动化,您必须考虑使用ORM ,它可以完全满足您的需求。 You can take a look at Eloquent for example. 例如,您可以看一下Eloquent So, the code would be as simple and straightforward as 因此,代码将像

$ftime = new fixedTime;
$ftime->value = time();
$ftime->save();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM