Sunday, February 24, 2013

PHP, using implode to insert array in MySQL

PHP implode function is used to join array elements with a string.  We can use implode function to insert array in MySQL. In this way, we only need to change array configuration and use generic  insert function. Suppose we want to insert 'admin321', 'my_pass', '' into MySQL table my_table with column 'login_name', 'password' and 'email', we can use the following code. For insert new values, we only need to redefine  $array.

// array containing data
$array = array(
"login_name" => "admin321",
"password" => "my_pass",
"email" => ""

// build query...
$sql  = "INSERT INTO my_table";

// implode keys of $array...
$sql .= " (`".implode("`, `", array_keys($array))."`)";

// implode values of $array...
$sql .= " VALUES ('".implode("', '", $array)."') ";

// execute query...
$result = mysql_query($sql) or die(mysql_error());


No comments:

Post a Comment