How to Insert an Array Into MySQL in PHP

A PHP array is not formatted in such a way where you can easily insert its values into a MySQL table. Calling each array variable as part of an insert query can be lengthy, especially if the table has more than a few columns in it. Use the number of elements in the array to build a new string that contains all the elements in the array, whether it has five or 50 or any other number. Then call that variable as part of the MySQL query.

Instructions

    • 1

      Open the HTML file. Insert the cursor where you want to insert an array into MySQL. Type the following code:

      <?php

      $dbh = mysql_connect ($dbServer, $dbUser, $dbPassword);

      mysql_select_db ($dbName);

      Replace the variables with the values specific to your MySQL database. These lines open PHP and establish a connection to the database.

    • 2

      Type the following code:

      $arr = array("a", "b", "c", "d", "e");

      $cnt = count($arr) - 1;

      The first line creates a PHP array. Use any array in your PHP code as needed. The second line creates a variable that counts the number of elements in the array, minus one. Decreasing the count by one is important for the formatting of the final element in the array.

    • 3

      Type the following code:

      for ($i = 0; $i < $cnt; $i++) {

      $myArr .= "'$arr[$i]', ";

      }

      $myArr .= "'$arr[$cnt]'";

      The loop creates a new variable called $myArr that takes all but the last element in the array and formats them in a way better suited for use in an insert statement by putting each item in single quotes with a comma afterward. When the loop completes, the next line adds the final element from the array without appending the comma so as to not cause a syntax error in MySQL.

    • 4

      Type the following code:

      mysql_query("INSERT INTO test VALUES ($myArr);");

      ?>

      These lines submit the insert query to the MySQL database then close the PHP tag.

Related Searches:

References

Comments

Related Ads

Featured