1

How to check the array keys in php to store array values in mysql. I am trying to store the "id" if the array have ("message") AND ("message" AND "story") key.

Array

array (
  0 => 
  array (
    'message' => 'Insane!!!!!',
    'story' => 'Ankan shared TIMES NOW\'s video.',
    'created_time' => 
    array (
      'date' => '2016-02-16 17:15:49.000000',
      'timezone_type' => 1,
      'timezone' => '+00:00',
    ),
    'id' => '10154521329397892_10154555849367892',
  ),
  1 => 
  array (
    'story' => 'Ankan shared Filmydrama\'s video.',
    'created_time' => 
    array (
      'date' => '2016-02-12 14:05:15.000000',
      'timezone_type' => 1,
      'timezone' => '+00:00',
    ),
    'id' => '10154521329397892_10154545385862892',
  ),
  2 => 
  array (
    'story' => 'Ankan shared Kya Yehi Hain Acche Din?\'s video.',
    'created_time' => 
    array (
      'date' => '2016-02-12 03:34:32.000000',
      'timezone_type' => 1,
      'timezone' => '+00:00',
    ),
    'id' => '10154521329397892_10154544563382892',
  ),
  3 => 
  array (
    'story' => 'Ankan shared a link.',
    'created_time' => 
    array (
      'date' => '2016-02-12 03:28:09.000000',
      'timezone_type' => 1,
      'timezone' => '+00:00',
    ),
    'id' => '10154521329397892_10154544555572892',
  ),
  4 => 
  array (
    'message' => 'R.I.P Jaihind',
    'story' => 'Ankan shared The Hindu\'s post.',
    'created_time' => 
    array (
      'date' => '2016-02-11 07:46:59.000000',
      'timezone_type' => 1,
      'timezone' => '+00:00',
    ),
    'id' => '10154521329397892_10154542597202892',
  ),
  5 => 
  array (
    'story' => 'Ankan posted from Change.org.',
    'created_time' => 
    array (
      'date' => '2016-02-11 05:09:08.000000',
      'timezone_type' => 1,
      'timezone' => '+00:00',
    ),
    'id' => '10154521329397892_10154542373792892',
  ),
  6 => 
  array (
    'message' => 'Johnson & Johnson Finally Admits: Their Baby Products Contain Cancer-Causing Chemicals | ',
    'created_time' => 
    array (
      'date' => '2016-02-11 01:38:33.000000',
      'timezone_type' => 1,
      'timezone' => '+00:00',
    ),
    'id' => '10154521329397892_10154542027992892',
  ),
  7 => 
  array (
    'story' => 'Ankan shared a link.',
    'created_time' => 
    array (
      'date' => '2016-02-09 17:16:07.000000',
      'timezone_type' => 1,
      'timezone' => '+00:00',
    ),
    'id' => '10154521329397892_10154538723082892',
  ),

I tried with the following code, but it is not giving anything.

$total_posts = array();
    $posts_response = $posts_request->getGraphEdge();
    if($fb->next($posts_response)) {
        $response_array = $posts_response->asArray();
        $total_posts = array_merge($total_posts, $response_array);
        while ($posts_response = $fb->next($posts_response)) {  
            $response_array = $posts_response->asArray();
            $total_posts = array_merge($total_posts, $response_array);  
        }
        $array = json_encode($total_posts, true);

    } else {
        $posts_response = $posts_request->getGraphEdge()->asArray();
        print_r($posts_response);
    }


    $my_arr = json_decode($array, true);

    ob_start();
    $data = var_export($my_arr);
    ob_end_clean();


    /*$story = $data;
    foreach( $my_arr as $row ) 

            $story .= " $row[message]\n";        

    $message_id = $data;
    foreach( $my_arr as $row ) 

            $message_id .= " $row[id]\n";*/


 $total_posts[0] = array('message', 'story', 'created_time', array('date', 'timezone_type', 'timezone'),'id');


    foreach ($total_posts as $row) {
      if (isset($row['story']) {
        if (isset($row['message']) {
          $message_id .= "$row[id]\n";
          $story .= " $row[message]\n";
        } else {
          // only story
        }
      } else {
        $message_id .= "$row[id]\n";
          $story .= " $row[message]\n";
      }
    }

I would like to get the output like

-----------------------------------------------------------------
id                                   | Messages
-----------------------------------------------------------------
 10154521329397892_10154555849367892 | Insane!!!!!
 10154521329397892_10154542597202892 || R.I.P Jaihind
-----------------------------------------------------------------

The above id will be associated with the message if and only if "message" key exists in the array.

3
  • hmm.. you have to concat all $row['id'] to $message_id, i.e. finally you have a string like id\n10154521329397892_10154545385862892\n10154521329397892_10154544563382892\n...etc. Does your code print any messages? Commented Feb 18, 2016 at 17:23
  • This code nothing effect in the database. But the commented lines effects on database, using this I am getting all the id. Where as my requirement is to get the id of message only. Commented Feb 18, 2016 at 17:26
  • but you have not an associative array at $total_posts[0] due $total_posts[0] = array('message', 'story', 'created_time', array('date', 'timezone_type', 'timezone'),'id');. Can you update your question, I don't figure out what you need to see finally. What kind of record you want to save into database? Commented Feb 18, 2016 at 17:30

1 Answer 1

0

I hope I have understand the question right.

here you can remove some lines of code (no validity check included)

$total_posts = array();
$posts_response = $posts_request->getGraphEdge();
do {
    $response_array = $posts_response->asArray();
    $total_posts = array_merge($total_posts, $response_array);  
} while ($posts_response = $fb->next($posts_response))
$array = json_encode($total_posts, true);
ini_set('display_errors', true);
try {
    $stmt = $db->prepare("insert into `<table>` (`id`,`message`) values(?,?);");
    $message_ids = array();
    $stories = array();
    foreach ($total_posts as $row) {
        if (isset($row['message'])) {
            // any record with 'message' is allowed
            // whenever has it 'story' or no
            $message_ids[] = $row['id'];
            $stories[]     = $row['message'];

        } else {
            if (isset($row['story'])) {
                // only story
            } else {
                // no message & no story
            }
        }
    }

    $message_id = implode("\n",$message_ids);
    $story      = implode("\n",$stories);
    $stmt->bind_param("ss", $message_id, $story);
    if ($stmt->execute()) {
        // success
    } else {
        // error handler
        $error = $stmt->error;
        // debug
        echo $error.PHP_EOL;
        die();
    }

    // or output to console
    // echo 'id: '.$message_id.PHP_EOL;
    // echo 'message: '.$story.PHP_EOL;
    // echo PHP_EOL;    
} catch (\Exception $e) {
    // debug
    echo $e->getMessage();
}

Hope it helps.

Updated results:

id: 10154521329397892_1015455584936789210154521329397892_1015454259720289210154521329397892_10154542027992892
msg: Insane!!!!!R.I.P JaihindJohnson & Johnson Finally Admits: Their Baby Products Contain Cancer-Causing Chemicals |

I have no issues with database:

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| test               |
+--------------------+
2 rows in set (0,00 sec)

mysql> use test;
Database changed

mysql> create table `test` (`id` varchar(128), `msg` varchar(128));
Query OK, 0 rows affected (0,10 sec)

mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| test           |
+----------------+
1 row in set (0,00 sec)

mysql> explain `test`;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | varchar(128) | YES  |     | NULL    |       |
| msg   | varchar(128) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0,01 sec)

mysql>

/// console
[65] $ php ./a.php
id: 10154521329397892_10154555849367892
10154521329397892_10154542597202892
10154521329397892_10154542027992892
msg: Insane!!!!!
R.I.P Jaihind
Johnson & Johnson Finally Admits: Their Baby Products Contain Cancer-Causing Chemicals |

 /// back to mysql shell
mysql> select * from `test`;
+-----------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------+
| id                                                                                                        | msg                                                                                                               |
+-----------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------+
| 10154521329397892_1015455584936789210154521329397892_1015454259720289210154521329397892_10154542027992892 | Insane!!!!!R.I.P JaihindJohnson & Johnson Finally Admits: Their Baby Products Contain Cancer-Causing Chemicals |  |
+-----------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------+
1 row in set (0,00 sec)

mysql>
Sign up to request clarification or add additional context in comments.

26 Comments

@user1328007 , and no any errors messages? :( , I've updated the code, can you try it?
No error. I think we have to enter the condition before inserting into the database. I would like to insert the value of "id" when ever there is a "message" key from the given example in the json format. So in the example I have exactly 3 message_id
@user1328007 , are you sure, that you have opened database, correct sql-query and corresponding table structure? I have tested the code, it shows result correct.
Its coming, but not the exact way which I want, I want that in my db, all message_id should be one field, and all message should be another field. But your code creates rows as the total number of message id exists
Ah.. any item separator needed?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.