【问题标题】:Two dimensional array dynamically in javascript and foreach loop in phpjavascript中的二维数组和php中的foreach循环
【发布时间】:2026-01-30 02:25:02
【问题描述】:

我正在使用 jquery 上传图像,在 jquery ui 对话框中,显示图像及其标题文本框,结果如下:

<ul id="image-list">
<li class="image-uploaded"><img src="www.site.com/gallery/e119f2-41dffd-678293-57c6db-7c665e-938481.png" class="thumb" rel="e119f2-41dffd-678293-57c6db-7c665e-938481.png"> <input id="ee773a0fee4669064560ad260cbfa2e8" name="title[]" class="input" style="width: 390px;" rel="e119f2-41dffd-678293-57c6db-7c665e-938481.png" type="text"></li>

<li class="image-uploaded"><img src="www.site.com/gallery/2658bc-992627-b4a698-f4e6f3-5719dd-d6b991.png" class="thumb" rel="2658bc-992627-b4a698-f4e6f3-5719dd-d6b991.png"> <input id="c8ca272704576fb747c5c2d76e582a4c" name="title[]" class="input" style="width: 390px;" rel="2658bc-992627-b4a698-f4e6f3-5719dd-d6b991.png" type="text"></li>

<li class="image-uploaded"><img src="www.site.com/gallery/813474-8551a5-896321-f2d8a1-bc5535-925d95.png" class="thumb" rel="813474-8551a5-896321-f2d8a1-bc5535-925d95.png"> <input id="288b465ab28b29f31889aea530e51bb3" name="title[]" class="input" style="width: 390px;" rel="813474-8551a5-896321-f2d8a1-bc5535-925d95.png" type="text"></li>

现在,我想在文本框中获取图像的名称和标题,使用$.post 方法发送,并在ajax.php 页面中将它们插入到数据库中。

我的 jQuery 代码部分是这样的:

var array = [];   
$.each($("input[name='title[]']"), function(index, value) {
    array.push($(this).attr('rel'), $(this).val());
});
$.post('ajax.php', {ImgSave:1, images: array, gallery_id : 5}, function(result) {
    $("#msg").html(result);
});

最后,ajax.php 中的 PHP 部分如下所示:

$no = $_POST["gallery_id"];
$images = $_POST["images"];
foreach ($images as $image => $title):
    $sql = "INSERT INTO gallery (gal_id, image, title) VALUES ('$no', '$image', '$title')";
    mysqli_query($connection,$sql); 
endforeach;

但它没有工作。我正在发送一张图像,但在 foreach 循环中,它返回 2 次。第一次显示图像名称,如e119f2-41dffd-678293-57c6db-7c665e-938481.png,第二次显示标题。 你能帮帮我吗?

【问题讨论】:

  • array.push({$(this).attr('rel'), $(this).val()});,这样你就可以连接名字和标题...没有括号,你将它们分别推入数组
  • 应该是:array.push([$(this).attr('rel'), $(this).val()]);
  • @Mr.Manhattan - array.push({$(this).attr('rel'), $(this).val()}); 返回错误。

标签: javascript php jquery multidimensional-array


【解决方案1】:

当您将两个参数传递给Array.prototype.push() 时,您只需将两个元素推送到数组中。

我怀疑你想要这个:

array.push(<b>[</b>$(this).attr('rel'), $(this).val()<b>]</b>);

为每张图片推送一个数组

在你的 PHP 文件中

$no = post("gallery_id");
$images = $_POST["images"];
$sql = "INSERT INTO gallery (gal_id, image, title) VALUES (?, ?, ?)";
$stmt = mysqli_prepare($connection, $sql); // Use prepared statements!
foreach ($images as $imageDetails):
    //Query is prepared once, and executed multiple times with different
    //parameters!
    mysqli_stmt_bind_param($stmt, "iss", $no, $imageDetails[0], $imageDetails[1]);
    //The details are now in array form, so [0] is the 'rel' and [1] is 'value'
    mysqli_stmt_execute($stmt);
endforeach;

【讨论】:

  • 非常感谢。我无法通过谷歌搜索找到。我还是不明白。但我会研究准备好的陈述。
  • 请做。否则您将面临 SQL 注入攻击。