gpt4 book ai didi

php - 通用快速编码 PHP MySQL 动态插入/更新查询创建表/字段命名为变量如果不存在

转载 作者:行者123 更新时间:2023-11-29 02:00:16 25 4
gpt4 key购买 nike

我正在寻找一种使 MySQL 插入/更新查询更加动态和快速编码的方法,因为有时只需要表单中的另一个字段(例如,原型(prototype)制作应用程序时)。这可能是一个愚蠢的问题。

我的想法是,如果 ID 匹配,则进行插入或更新,如果表/字段不存在,则使用一个函数动态创建它。

<?php 
// $l is set with some db-login stuff

// creates and inserts
$f[] = nf(1,'this_id_x'); // this_id_* could be a prefix for ids
$f[] = nf('value yep',$fieldname_is_this2)
$tbl_name = "it_didnt_exist";
nyakilian_fiq($l, $tbl_name, $f);
// Done!


//This would do an update on above
$fieldname_is_this2 = "this is now updated";
$f[] = nf(1,'this_id_x');
$f[] = nf($fieldname_is_this2); // the function takes the variable name as field name
$tbl_name = "it_didnt_exist";
nyakilian_fiq($l, $tbl_name, $f);

?>

最佳答案

我一直在成功地使用这个功能。它不添加列,但这与我的 MVC 框架的结构不符。尝试这样的事情:

public function save(DatabaseConnection &$db)
{
$properties = get_object_vars($this);
$table = $this->getTableName();
// $cols = array();
// $values = array();
foreach ($properties as $key => $value) {
$cols[] = "`$key`";
$values[] = '"'.$value.'"';
if ($value != NULL) {
$updateCols[] = "`$key`".' = "'.$value.'"';
}
}

$sql = 'INSERT INTO '.$table.' ('.implode(", ", $cols).') VALUES ('.implode(", ", $values).') ON DUPLICATE KEY UPDATE '.implode(", ", $updateCols);

$stmnt = $db->prepare($sql);
var_dump($stmnt);
if ($stmnt->execute($values)) return true;
return false;
}

我有一个模型抽象类,我为每个数据库表扩展了一个子类。该函数位于模型摘要中。每个子类都包含一个公共(public)属性 [因此我可以使用 PDO::fetchObject()] 对应于表中的列名。如果我需要即时创建表,我会向子类添加一个函数来执行此操作。

关于php - 通用快速编码 PHP MySQL 动态插入/更新查询创建表/字段命名为变量如果不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16667204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com