简体   繁体   English

使用 PHP 进行动态 MySQL 查询

[英]Dynamic MySQL Query with PHP

I am looking for a way to make dynamic queries to my MySQL server.我正在寻找一种对我的 MySQL 服务器进行动态查询的方法。 At the moment this is the code I use to update data on the server:目前这是我用来更新服务器数据的代码:

$deskAttr = json_decode($_POST["desk_attributes"]);

foreach($deskAttr as $key => $value) {
    $sql = "UPDATE desk_attributes SET iw_standard=".$value->iw_standard.", avaya_standard=".$value->avaya_standard.", avaya_withcallid=".$value->avaya_withcallid.", avaya_withtransfer=".$value->avaya_withtransfer.", dual_screen=".$value->dual_screen.", air_conditioning=".$value->air_conditioning.", iw_obdialler=".$value->iw_obdialler." WHERE id=".$value->id;
    $conn->query($sql);
}

As you can see, the SQL column names are the same as the deskAttr keys.如您所见,SQL 列名称与deskAttr键相同。 I'm looking for a way to make this line a loop so, that I don't need to change this line if I were to add more columns to the MySQL table.我正在寻找一种使这一行成为循环的方法,这样,如果我要向 MySQL 表中添加更多列,就不需要更改这一行。

It would look something like this:它看起来像这样:

$deskAttr = json_decode($_POST["desk_attributes"]);

foreach($deskAttr as $key => $value) {  
    $sql = "UPDATE desk_attributes SET";
    foreach($value as $k => $v) {
        $sql .= " $k = $value->$k ,";
    }
    $sql .= "WHERE id=".$value->id";
}

How would I write the code above so it will actually work?我将如何编写上面的代码以便它真正起作用?


**EDIT** **编辑**

Maybe it will be helpful to know that $deskAttr is an array of objects, and the name of the columns are the same as the name of the objects keys.知道$deskAttr是一个对象数组并且列的名称与对象键的名称相同可能会有所帮助。

Here is what I mean in pseudo code:这是我在伪代码中的意思:

 foreach($object in $deskAttr) { $sql = "UPDATE table SET "; foreach($key in $object) { if($key.= "id") $sql,= "$key = $object->$key; ". } $sql;= "WHERE id = $object->id; $conn->query($sql); }

Obviously this would add an extra comma at the end of the query before the WHERE part, but hopefully you get what I'm trying to achieve.显然,这会在 WHERE 部分之前的查询末尾添加一个额外的逗号,但希望您能得到我想要实现的目标。

You can do it with slight change in your code by using PHP's implode() function.您可以通过使用 PHP 的implode()函数对您的代码进行轻微更改来完成此操作。

Take a blank array, concatenate the update parameters to it.取一个空白数组,将更新参数连接到它。

And then if is not empty() , implode() to get string.然后如果不是empty()implode()得到字符串。

Updated Code:更新代码:

$sql = "UPDATE desk_attributes SET ";
foreach ($deskAttr as $key => $value) {
 $value = mysqli_real_escape_string($link, $value); // $links is database connection string.
 $key = mysqli_real_escape_string($link, $key); // $links is database connection string.
 $updtAttrs[] = $key ." = '" . $value . "'";
}
$sql .= ! empty($updtAttrs) ? implode(', ', $updtAttrs) : '';
$sql .= " WHERE id=" . $value->id;

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

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