我正在尝试组合一个执行以下操作的函数:
- 从表单中检索 JSON 编码的字符串
- 将字符串解码为 php 数组
- 遍历生成的 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/