简体   繁体   English

将数组值赋给变量并使用PHP插入mysql

[英]Assign Array Value to Variable and Insert into mysql using PHP

I am trying to save array value to variable so that I can insert that data/value into mysql using PHP for that I am using a pain taking long code so I want simple method to do it without writing it again and again. 我试图将数组值保存为变量,以便我可以使用PHP将数据/值插入mysql,因为我花了很长时间才能编写代码,所以我想用简单的方法来做到这一点,而不必一次又一次地编写它。

Array shows data like this 数组显示这样的数据

Array
(
    [0] => Array
        (
            [0] => a><p class="wp-caption-text">Pendant Heart Images</p></div>
            [1] => a><p class="wp-caption-text">Pendant Heart Photos</p></div>
            [2] => a><p class="wp-caption-text">Pendant Heart Photos</p></div>
        )

    [1] => Array
        (
            [0] => Pendant Heart Images
            [1] => Pendant Heart Photos
            [2] => Pendant Heart Photos

      )

)

Code which I am using to save array value 我用来保存数组值的代码

$a = $g_img[1][0];
$b = $g_img[1][1];
$c = $g_img[1][2];

$a1 = $title[1][0];
$b1 = $title[1][1];
$c1 = $title[1][2];

Mysql query to save data MySQL查询保存数据

mysqli_query($con,"INSERT INTO data (Link, Title) VALUES ('$a','$a1')");
mysqli_query($con,"INSERT INTO data (Link, Title) VALUES ('$b','$b1')");
mysqli_query($con,"INSERT INTO data (Link, Title) VALUES ('$c','$c1')");

So If array data increases I have to assign each array value to different variable which is huge process I know there would be a shortcut 因此,如果数组数据增加,我必须将每个数组值分配给不同的变量,这是一个巨大的过程,我知道会有捷径

Plz Help 请帮助

The query will not work because to start with, the number of field name are not equal to the number of values. 该查询将不起作用,因为开始时字段名称的数量不等于值的数量。

You could have passed your query in the following way: 您可以通过以下方式传递查询:

for ($counter = 0; $counter <=2; $counter++){
    $query = "INSERT INTO data (Link, Title) VALUES ('{$g_img[1][$counter]}', '{$title[1][$counter]}')";
    $result = mysqli_query($con, $query);

}

Here I have assumed that $g_img and $title correspond to the array of links and titles respectively and the data connection is $con . 在这里,我假设$g_img$title对应于链接和标题的数组,并且数据连接为$con

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

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