php - 从 JSON 返回的结果插入到 mysql 表中,然后通过电子邮件发送结果

标签 php mysql json sendmail

我需要帮助了解如何将 JSON 数组的返回结果插入到 SQL 表中,然后通过电子邮件发送返回的结果。

下面是我到目前为止成功将查询结果获取到 JSON 数组的 php 脚本

<?php

    // set up the connection variables
    $db_name  = 'dbanme';
    $hostname = 'host';
    $username = 'username';
    $password = 'password';

    // connect to the database
    $dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);

    // a query get all the records from the users table
    $sql = 'SELECT tabel1.id,table1.type FROM table1 LEFT JOIN table2 ON table1.id=table2.id WHERE table1.id NOT IN ( SELECT table2.id FROM table2)';

    // use prepared statements, even if not strictly required is good practice
    $stmt = $dbh->prepare( $sql );

    // execute the query
    $stmt->execute();

    // fetch the results into an array
    $result = $stmt->fetchAll( PDO::FETCH_ASSOC );

    // count number of results returned in the array
    $countresults = count($result);
    echo $countresults;


    if ( $countresults > 0 ) {

    // convert to json
    $json = json_encode( $result );

    // decode the results returned and insert them into table 2

    // email the results returned


    }

    else {
        echo ' no results found';
    }

?>

更新: 表1结构: ID 整数 10 类型 VARCHAR 50

表2结构: ID 整数 10 类型 VARCHAR 50

我意识到我不需要将结果编码为 JSON,但我仍然无法获取代码来获取从数组返回的结果并将它们插入到 tabl2 中,然后直接通过电子邮件发送结果。

最佳答案

首先,您必须告诉我们为什么将结果转换为 json。您已经有一个数组,在您的情况下不需要 JSON 字符串。

无论如何,您可以将 JSON 字符串转换回数组,如下所示:

$yourArray = json_decode($json)

现在您说要将数据插入表二。我不知道你的表是什么样子的,但是如果我看看你的代码,我猜你的sql会是这样的:

$sql = 'INSERT INTO table2(id, type) VALUES (:id, :type)';

所以你的代码看起来像这样:

$sql = 'INSERT INTO table2(id, type) VALUES (:id, :type)';
$stmt->bindParam(':id', $yourArray ['id']);
$stmt->bindParam(':type', $yourArray['type']);
$stmt = $dbh->prepare( $sql );
$stmt->execute();

如果您想通过邮件发送结果,只需使用默认的邮件功能即可:

$to = 'RECIEVER@MAIL'
$subject = 'SUBJECT';
$message='Your values are: '.$yourArray ['id'].' - '.$yourArray['type'];

mail($to,$subject,$message);

如果默认邮件功能不起作用,您的服务器可能不允许(有时出于安全原因)。在这种情况下,我建议使用第三方库,例如 PHPMailer

你的问题没有透露很多信息,我已经尽力了,但上面的代码仍然更多是伪代码。

关于php - 从 JSON 返回的结果插入到 mysql 表中,然后通过电子邮件发送结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27874507/

相关文章:

php - 通过 jQuery 过滤图像集合

mysql - 体育评分系统的数据库设计

php - 单击行以使用其数据预填充表单仅显示第一条记录

json - 使用 RESTeasy 和 Jettison 将对象编码为 JSON 时忽略空值

json - 将 JSON 数据从 $http 发送到 Node JS Express Restful 服务

php - 如何在MySQL中删除带有子级的多级菜单项?

php - 将类型数值从字符串转换为整数而不更改其值

php - HTML mySQL 表单不起作用

php - MySQL 需要帮助定义 SQL 以删除不需要的行

php - 优化 mysql 日期生成器?