Insert PHP Array into MySQL Database Table as Row or Field

2 minute read
0
Insert PHP Array into MySQL Database Table as Row or Field

This post will show you how insert an array in PHP to MySQL database, there is two needed ways that you may utilize from the array, the first to insert it as a row, or to insert it in one field to retrieve it later.

Inserting PHP array into MySQL Database Table as Row

some times you need to insert an array to be a row in a MySQL table, to turn out the idea , suppose  you have the following MySQL table:

CREATE TABLE `wp_templates` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`template_type` varchar(255) NOT NULL,
`template_name` varchar(255) NOT NULL,
`template_path` varchar(255)  NOT NULL,
PRIMARY KEY (`ID`)
)  ;

and suppose you have also the following array:

<?php

$template = array( ‘template_type’ => ‘static’ ,  ‘template_name’ => ‘Latest News’ , ‘template_path’ => ‘/templates/last_news.php’);

?>

you may want the code that will add this array to the table shown above, the code is very simple as the following:

 <?php

//Firstly we get the array keys to be the MySQL column names.

$mysql_cols = implode(“, “,array_keys($template));

//We escape values in array for security reasons.

$mysql_values = array_map(‘mysql_real_escape_string’, array_values($template));

// Prepare the array values to be the sql row values.

$mysql_values  = implode(“, “, $mysql_values );

// Just write the MySQL statement as the following.

$sql = “INSERT INTO `wp_templates`($mysql_cols ) VALUES ($mysql_values)”;

?>

Inserting PHP array into MySQL Database Field as String

To insert array as a string in MySQL database, you have to use the function serialize() which will convert the array into sting representation that can be saved into array, later if you want to restore the array, you have to use the PHP function unserialize() as the following:

<?php

$string_template = serialize($template );

// just insert the variable $string_template

// when you need to restore the array, as the following:

$template= unserialize($string_template);

?>

× Shopping Cart

Your cart is empty.