从 JSON 返回的结果插入 mysql table,然后通过电子邮件发送结果

Returned results from JSON to insert into mysql table and then email the results

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

下面是我的 php 脚本,它成功地将查询结果放入 JSON 数组

<?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';
    }

?>

更新: Table 1 个结构: 识别码整数 10 输入 VARCHAR 50

Table 2 结构: 识别码整数 10 输入 VARCHAR 50

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

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

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

$yourArray = json_decode($json)

现在你说要插入数据到table二。我不知道你的 table 是什么样子,但如果我看你的代码,我猜你的 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

这样的第三方库

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