php mysql更新从表单值生成语句

发布于 2024-08-19 22:16:41 字数 460 浏览 3 评论 0原文

我正在创建一个非常小的数据库抽象层,我想发送从表单获得的变量数组,并生成更新sql语句,并最终执行它。 我应该在下面倒数第二行放什么? 例如。

$table name = "user";
$username = $_post['username'];
$password = $_post['password'];
$email    = $_post['email'];
$array = (username=>$username, password=>$password, email=>$email);
$query = "update $this->tableName".
$query = """" The value from the assc array in the form of database value='form value' 
$query = "WHERE condition";

I am creating a very small database abstract layer, i want to send an array of variables that i obtained from a form, and generate an update sql statement, and eventually execute it. What do I put on the second to last line below?
for example.

$table name = "user";
$username = $_post['username'];
$password = $_post['password'];
$email    = $_post['email'];
$array = (username=>$username, password=>$password, email=>$email);
$query = "update $this->tableName".
$query = """" The value from the assc array in the form of database value='form value' 
$query = "WHERE condition";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北凤男飞 2024-08-26 22:16:41

您可以使用 foreach() 循环从数组生成查询子句。请注意,您需要使用 array() 构造声明数组,并引用关联键。

//...
$array = array('username'=>$username, 'password'=>$password, 'email'=>$email);
$query = "update ".$this->tableName." SET ";
foreach($array as $field => $value) {
    $query .= "`".$field."`='".mysql_real_escape_string($value)."',";
}
//knock off trailing comma
$query = substr($query,0,-1);
$query .= " WHERE condition";

You can use a foreach() loop to generate your query clause from your array. Note that you need to declare your array with the array() construct, and quote your associative keys.

//...
$array = array('username'=>$username, 'password'=>$password, 'email'=>$email);
$query = "update ".$this->tableName." SET ";
foreach($array as $field => $value) {
    $query .= "`".$field."`='".mysql_real_escape_string($value)."',";
}
//knock off trailing comma
$query = substr($query,0,-1);
$query .= " WHERE condition";
微暖i 2024-08-26 22:16:41

您可以使用类似的内容:

$a = array();
foreach($array as $key => $value)
{
    $a[] = $key . " = '" . mysql_real_escape_string($value) ."'";
}
$query = join(',', $a);

但您需要处理特殊情况,例如当值为 null 或日期时

You can use something like:

$a = array();
foreach($array as $key => $value)
{
    $a[] = $key . " = '" . mysql_real_escape_string($value) ."'";
}
$query = join(',', $a);

but you need to take care of special cases, for example when the value is null or a date

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文