Salvare un array nel DB con PHP!
Posted on 02. Jan, 2010 by daniele in php, tutorials
In questo tutorial imparerete come salvare (e leggere successivamente) un array criptato all'interno di un record MySQL.
< ?php function store_encrypt($array) { // Start function with function name store_encrypt. if (!is_array($array)) { // Check if $array is an array or not if it isnt return false. return false; // return false. } else { foreach ($array as $key => $value) { // Cycle through the array. $key = base64_encode($key); // Encode the key with base 64. $value = base64_encode($value); // Encode the value with base 64. $array[$key] = $value; // Put the key and value back into the array } return serialize($array); // Use the PHP serialize function to save the array, type and values and return the function. } } function unstore_uncrypt($value) { // Start function with function name unstore_uncrypt. if (!is_array($array)) { // Check if $array is an array or not if it isnt return false. return false; // return false. } else { $array = unserialize($value); // Restore the value into an array. foreach ($array as $key => $value) { // Cycle through the array. $key = base64_decode($key); // Decode the key from base 64. $value = base64_decode($value); // Decode the value from base 64. $array[$key] = $value; // Put they key and value back into the array. } return $array; // Return the array. } } $conn = mysql_connect("DATABASE_LOCATION","DATABASE_USER","DATABASE_PASSWORD"); // Connect to mysql server if (!$conn) die ("Could not connect MySQL"); // If unable to connect die mysql_select_db("DATABASE_NAME",$conn) or die ("Could not open database"); // Now your connected select the correct database $array = array("first_name" => "Peter", "last_name" => "Kelly", "website" => "http://www.pk-tuts.co.uk"); // Create the array. $info = store_encrypt($array); // Run the function $add_array = mysql_query("INSERT into `table` (`id`, `array`) values ('', '".$info."');"); // Insert into the table $result = mysql_query("SELECT * FROM `table` ORDER BY `id` DESC LIMIT 1"); // Select one row from table and order by id descending. $r = mysql_fetch_array($result); // Select the data. $uncrypt = unstore_uncrypt($r['array']); // Get the array stored in the database and run the function to uncrypt it echo "
"; // Do some formatting so the array looks pretty. print_r($uncrypt); // Echo the array. echo ""; ?>


Leave a reply