1

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.

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

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

2
  • How is that MySQL query supposed to work? Commented Mar 30, 2014 at 19:12
  • I have updated MySQL query check @TheWolf Commented Mar 30, 2014 at 19:19

1 Answer 1

1

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.

3
  • yeah thanks it's working for me tell me if array increases from 2 to 10 should I change <=2 to <=10 Commented Mar 30, 2014 at 19:26
  • How to ignore empty array like if array [1][0] => empty Commented Mar 30, 2014 at 19:41
  • The function count() will help you in this too just put it in an if-conditional. Commented Mar 30, 2014 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.