Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- table:------------
- CREATE TABLE IF NOT EXISTS `user_meta` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `user_id` int(11) NOT NULL,
- `option_name` varchar(50) NOT NULL,
- `option_value` varchar(50) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
- // default insert -------------->
- INSERT INTO `user_meta` (`id`, `user_id`, `option_name`, `option_value`) VALUES (1, 1, 'name', 'Joe'),(2, 1, 'age', '28'),(3, 1, 'gender', 'male'),(4, 2, 'name', 'jane'),(5, 2, 'age', '26'),(6, 2, 'gender', 'female');
- */
- ini_set('display_errors', 1);
- error_reporting(1);
- $mysql= new mysqli('localhost', 'root', 'root', 'test');
- // new row values ---------------->
- $new_row=array(
- 'name'=>'Donny',
- 'age'=>'30',
- 'gender'=>'male',
- 'country'=>'us'
- );
- $user_id='3';
- // get old rows from DB ------------>
- $old_rows=$mysql->query("SELECT user_id from user_meta where user_id='".$user_id."'");
- // if there are no rows or "$old_rows->num_rows" row count is not equal to "" count for user id ----------------->
- if( $old_rows->num_rows==0 || count($new_row)!=$old_rows->num_rows )
- {
- // if current row count is not equal to new row count removing old rows from table -------------->
- if($old_rows->num_rows>0){
- $result=$mysql->query("DELETE from user_meta where user_id='".$user_id."'");
- }
- // inserting new rows ------------------>
- $qry= "INSERT INTO user_meta (user_id,option_name,option_value)";
- foreach($new_row as $index=>$value){
- $values[]="'".$user_id."', '".$index."','".$value."'";
- }
- $qry .=' VALUES ('.implode('),(',$values).')';
- if($result=$mysql->query($qry)){
- echo 'inserted';
- }else{
- echo $mysql->error;
- }
- // if rows are same update ------------->
- }else{
- $qry .= "UPDATE `user_meta` SET option_value = CASE option_name";
- foreach($new_row as $index=>$value){
- $qry .= " WHEN '".$index."' THEN '".$value."' ";
- $indexes[]=$index;
- }
- $qry .= "END WHERE user_id ='".$user_id."' AND `option_name` IN ( '".join($indexes,"','")."') ";
- if($result=$mysql->query($qry)){
- echo 'updated';
- }else{
- echo $mysql->error;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement