来自 php 数组的简单更新 MySQl 表 [英] Simple UPDATE MySQl table from php array

查看:60
本文介绍了来自 php 数组的简单更新 MySQl 表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to put together a function that does the following:

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

这是我目前的函数代码:

Here is my function code so far:

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 变量中的数组:

Here is the array stored in the $update_array variable:

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 步.

I have got steps 1 and 2 working fine, however I am stuck on step 3.

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

I still learning PHP and struggle with syntax at times. I have tried to work this one out on my own and have spent several hours on it, but just can't seem to figure this one out.

非常感谢任何帮助.

推荐答案

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 数组的简单更新 MySQl 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆