php - 从 php 数组简单更新 MySQl 表

标签 php mysql arrays

我正在尝试组合一个执行以下操作的函数:

  1. 从表单中检索 JSON 编码的字符串
  2. 将字符串解码为 php 数组
  3. 遍历生成的 php 数组以获取数组每个部分的值,以便我可以更新 MySql 表

到目前为止,这是我的功能代码:

public function saveTestimonials() {


    $existing_testimonials_update = $this->post('data');

    $update_array = json_decode($existing_testimonials_update);

    foreach ($update_array as $key => $testimonials) {
         foreach($testimonials as $key => $value) {
            //echo "$key = $value\n";

        }
    }

    $db = Loader::db();
    $sql = "UPDATE testimonials SET name=var, content=var WHERE id=var";
    $db->query($sql);

    $this->redirect('/dashboard/testimonials/');

}

这是存储在 $update_array 变量中的数组:

Array
(
[0] => stdClass Object
    (
        [id] => 1
        [name] => Mr. John Doe, Manager, ABC Ltd
        [content] => my content 1.
    )

[1] => stdClass Object
    (
        [id] => 2
        [name] => Mr. Joe Smith, Manager, ABC Industries
        [content] => my content 2.
    )

[2] => stdClass Object
    (
        [id] => 3
        [name] => Mr. Mike Smith, Manager, ABC Industries
        [content] => my content 3.
    )

[3] => stdClass Object
    (
        [id] => 4
        [name] => Ms. Jane Doe, Manager, ABCD Ltd
        [content] => my content 4.
    )

)

我的第 1 步和第 2 步工作正常,但我卡在了第 3 步。

我仍在学习 PHP 并且有时会在语法上挣扎。 我试图自己解决这个问题并花了几个小时,但似乎无法解决这个问题。

非常感谢任何帮助。

最佳答案

foreach ($update_array as $key => $testimonials) {
    $name = mysql_real_escape_string($testimonials->name);
    $content = mysql_real_escape_string($testimonials->content);
    $id = intval($testimonials->id);

    $sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id=$id";
    $result = mysql_query($sql);
    if ($result === FALSE) {
        die(mysql_error());
    }
}

关于php - 从 php 数组简单更新 MySQl 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7884284/

相关文章:

mysql - 何时使用左外连接?

php - 如何将数组转换为带索引的字符串

java - 从行列表中获取数组?

php - 为什么这个 php 脚本不给我发邮件?

PHP HTML DOM 解析器

c# - Mysql 没有出现在 Visual Studio 2017 的 "Choose Data Source"中

c++ - 使一维指针数组指向二维 vector 中的对象

php - 如果不存在则创建表 - 意外的 T_STRING

php - 在 PDO 事务中创建表

php - 如何将复选框添加到数据表以用于删除所选行?