Advertisement
LTroya

Unir datos de 2 bases de datos diferentes

Nov 8th, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.24 KB | None | 0 0
  1. <?php
  2.  
  3. function connect($host = 'localhost', $dbname = 'voip', $user = 'homestead', $password = 'secret')
  4. {
  5.     try {
  6.         $conn = new pdo("mysql:host=$host;dbname=$dbname",
  7.             $user,
  8.             $password,
  9.             array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
  10.         return $conn;
  11.     } catch (PDOException $ex) {
  12.         die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
  13.     }
  14. }
  15.  
  16. $usuario = 'homestead';
  17. $contraseña = 'secret';
  18.  
  19. $conn = connect('localhost', 'voip', $usuario, $contraseña);
  20. $conn2 = connect('localhost', 'voip2', $usuario, $contraseña);
  21.  
  22. $sql1 = $conn->prepare("SELECT id, first_name, phone_number FROM bit_gxp_phonebook");
  23. $sql1->execute();
  24.  
  25. $sql2 = $conn2->prepare("SELECT id, first_name, phone_number FROM bit_gxp_phonebook");
  26. $sql2->execute();
  27.  
  28. $response1 = $sql1->fetchAll();
  29. $response2 = $sql2->fetchAll();
  30.  
  31. $results = array_merge($response1, $response2);
  32.  
  33. $json_data = [];
  34.  
  35. for ($i = 0; $i < count($results); $i++) {
  36.     $item = [
  37.         'id' => $results[$i]['id'],
  38.         'fist_name' => $results[$i]['first_name'],
  39.         'phone_number' => $results[$i]['phone_number']
  40.     ];
  41.  
  42.     $json_data[] = $item;
  43. }
  44.  
  45. print_r(json_encode($json_data));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement