This is the most important technique for all Php developers because of Mysql can't store the array values directly.
So we need to convert the PHP Array to string by using the serialize().
This mechanism is very useful in the e-commerce cart functionality. For example, we can store the customer purchase items list and price can be stored in the associative array and convert into string and store in the MySQL.
This way we can reduce the logic of the code get the accurate result also.
MySql Code
You need to connect the database create the dbconfig.php file
Now Store the PHP Array in MySql create the store-array.php file
Now retrieve the PHP Array from MySQL create the retrieve-array.php file
Here you can download the Full Source code and check the demo.
Download Demo
So we need to convert the PHP Array to string by using the serialize().
This mechanism is very useful in the e-commerce cart functionality. For example, we can store the customer purchase items list and price can be stored in the associative array and convert into string and store in the MySQL.
This way we can reduce the logic of the code get the accurate result also.
MySql Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | CREATE TABLE `students` ( `id` int (11) NOT NULL , `language` varchar (50) NOT NULL , `student_names` mediumtext NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for table `students` -- ALTER TABLE `students` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for table `students` -- ALTER TABLE `students` MODIFY `id` int (11) NOT NULL AUTO_INCREMENT; |
1 2 3 4 5 6 7 8 9 10 11 12 | <?php $servername = "localhost" ; $username = "root" ; $password = "" ; $dbname = "techiesbadi" ; // Create connection $con = new mysqli( $servername , $username , $password , $dbname ); // Check connection if ( $con ->connect_error) { die ( "Connection failed: " . $con ->connect_error); } ?> |
1 2 3 4 5 6 7 8 9 10 11 | <?php include "dbconfig.php" ; $students = array ( "ramu" , "ravi" , "gopal" , "krishna" ); //Converting array to String $student_names =mysqli_real_escape_string( $con , serialize( $students )); $sql = "INSERT INTO `students` (`id`, `language`, `student_names`) VALUES (NULL, 'php', '$student_names')" ; $result = $con ->query( $sql ); if ( $result === TRUE){ echo "Record inserted successfully" ; } ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php include "dbconfig.php" ; $getStudnets = $con ->query( "SELECT * FROM `students` LIMIT 1" ); $studentsData = $getStudnets ->fetch_object(); $language = $studentsData ->language; //Converting string to array $students = unserialize( $studentsData ->student_names); //printing students array print_r( $students ); echo "<br />" ; foreach ( $students as $student ) { echo $student . " learning " . $language . " language.<br/>" ; } ?> |
Download Demo
* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff