表情符号从Angularjs $ http到PHP json_decode并存储在mySQL中

时间:2018-05-24 09:41:51

标签: php mysql angularjs emoji

所以我试图将emojis存储在我的数据库中并在我的应用程序中返回它们。我用离子v1制作了一个小型的消息,一切正常。我只想正确存储表情符号并在应用程序中显示它们。我的整个数据库,表和列都设置为utf8mb4所以我知道这很好。当我将$http发送到我的php时,它也看起来很棒:{"from_account_id":"xxxx","for_account_id":"xxxx","message":""}:但是当我在php中打印它时,它看起来像这样:{"from_account_id":"106191","for_account_id":"989014","message":"đ˝"}并且在我的mysql到处都放了一个表情符号?。我还能做什么?我还将我的php中的标题设置为UTF_8。我知道有很多问题,但我已经跟随了他们中的大多数,但仍然没有解决我的问题。

我在php中存储消息:

<?php
header('Content-Type: text/html; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
include_once 'config.php';

$data = file_get_contents("php://input");
$data = json_decode($data, true);

try {
    $stmt = $dbh->prepare("INSERT INTO `messages` (`message_id`, `from_account_id`, `for_account_id`, `date_read`, `message`)
      VALUES (NULL, :from_account_id, :for_account_id, NULL, :message)");
    $stmt->bindValue(':from_account_id', $data['from_account_id']);
    $stmt->bindValue(':for_account_id', $data['for_account_id']);
    $stmt->bindValue(':message', $data['message']);
    $stmt->execute();
  } catch (PDOException $e) {
          throw $e;
  }
  echo 'Success';

?>

我发送邮件的AngularJS函数:

  $scope.sendMessage = function(for_account_id, message){
    if(for_account_id != null && message != null){
    $http({
      method: 'post',
      url: 'myurl',
      data: {
      from_account_id: $rootScope.unique_id,
      for_account_id: for_account_id,
      message: message,
      },
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(function successCallback(data){
      $scope.thisMessage = null;
      $scope.getMessages();
      $rootScope.webSocket.send($stateParams.chatId + "|" + $rootScope.unique_id  + "|" + 'newMessage');
      $scope.markAsRead();
    })
  }
  }

这是我与数据库的连接:

<?php
$hostname='myhost';
$username='myuser';
$password='mypassword';

$options = array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES utf8'); 

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=mydbname;charset=utf8mb4",$username,$password, $options);
    $dbh->query ('SET NAMES utf8');
    $dbh->query ('SET CHARACTER_SET utf8_unicode_ci');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
      echo $e->getMessage();
    }
?>

我想念的任何提示或想法?

1 个答案:

答案 0 :(得分:0)

Okey所以我已经解决了我的问题。我这样做的方式不是最好的,但它有效。所以基本上在数据库中存储unicodes就像那样简单:

  1. 我将我要插入数据的文件中的header更改为:

    header('Content-Type: application/json; charset=utf-8');

  2. 我再次将消息编码为json,同时插入它:

    $stmt->bindValue(':message', json_encode($data['message']));

  3. 在再次回复我的应用之前,将标题设置为:

    header('Content-Type: application/json; charset=utf-8');

  4. 我的代码现在看起来像这样:

    <?php
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET');
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    include_once 'config.php';
    
    $data = file_get_contents("php://input");
    $data = json_decode($data, true);
    
    try {
        $stmt = $dbh->prepare("INSERT INTO `messages` (`message_id`, `from_account_id`, `for_account_id`, `date_read`, `message`)
          VALUES (NULL, :from_account_id, :for_account_id, NULL, :message)");
        $stmt->bindValue(':from_account_id', $data['from_account_id']);
        $stmt->bindValue(':for_account_id', $data['for_account_id']);
        $stmt->bindValue(':message', json_encode($data['message']));
        $stmt->execute();
      } catch (PDOException $e) {
        header('Content-Type: text/html; charset=utf-8');
              throw $e;
      }
      header('Content-Type: text/html; charset=utf-8');
      echo 'Success';
    
    ?>
    

    所以这个问题已修复,unicodes存储在我的数据库中。

    然后我又在一个尴尬的情况下再次进行游戏,因为在从mysql获取数据并将其编码到json时发送到我的应用,我的应用无法将unicodes返回给特殊字符甚至我用ng-bind-html绑定它并使用$sce.trustAsHtml()。通常情况下,我只是将查询结果发送为encoded json,但它并没有像我说的那样工作。所以我所做的就是这样:

    <?php
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *'); 
    header('Access-Control-Allow-Methods: POST, GET');
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    include_once 'config.php';
    
    $data = file_get_contents("php://input");
    $data = json_decode($data, true);
    
    try {
      $stmt = $dbh->prepare("SELECT * from messages WHERE (from_account_id = :unique_id AND for_account_id = :user_2) OR (from_account_id = :user_2 AND for_account_id = :unique_id)");
      $stmt->bindValue(':unique_id', $data['user_1']);
      $stmt->bindValue(':user_2', $data['user_2']);
      $stmt->execute();
      } catch (PDOException $e) {
              throw $e;
          }
    
      $rows = $stmt->rowCount();
      $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
      if ($rows > 0){
        $i = 0;
        echo "[";
        foreach ($result as $key => $value){
          $i++;
          echo "{";
          echo '"message_id"' . ":" . '"' .$value['message_id']. '"' .", ";
          echo '"from_account_id"' . ":" . '"' .$value['from_account_id']. '"' .", ";
          echo '"for_account_id"' . ":". '"' .$value['for_account_id']. '"' .", ";
          echo '"date_sent"' . ":" . '"' .$value['date_sent']. '"' .", ";
          echo '"date_read"' . ":" . '"' .$value['date_read']. '"' .", ";
          echo '"message"' . ":" . '"' .str_replace("\n", "</br>", json_decode($value['message'])). '"' ;
          echo "}";
          if($i != $rows){
            echo ",";
          }
          if($i == $rows){
            echo "]";
          }
          echo "\n";
        }
        exit;
      }
      else {
        echo 'Something went wrong';
        exit;
      }
    
    ?>
    

    将解码后的json发送到我的angularjs作为我自己制作的真实json的字符串中解决。

    我已经在这个问题上添加了anwser,因为也许有人会遇到同样的麻烦,这会有所帮助。