如何从PHP fetch assoc获得结果

时间:2017-05-18 06:02:37

标签: javascript php html mysql slim

// Request password

$app->get('/api/admin/forgot', function(Request $request, Response $response){

$email = $request->getParam('email');
$sql = "SELECT admin_password FROM administrators WHERE admin_email = '$email' ";

try{

    $db = new db();
    $db = $db->connect();
    $stmt =  $db->query($sql);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    $db = null;

    if($admin == null){
        echo json_encode(array(
                                "errno" => 1,
                                "message" => "No account",
                            )
                        );
        return;

    }

    echo $admin;
    require_once "vendor/autoload.php";

    //PHPMailer Object
    $mail = new PHPMailer;

    //From email address and name
    $mail->From = "contact@SMS.com";
    $mail->FromName = "SAMPLES Management Software";
    //To address and name
    $mail->addAddress($email); 
    //Address to which recipient will reply
    $mail->addReplyTo("contact@SMS.com", "SAMPLE Management Software");
    //Send HTML or Plain Text email
    $mail->isHTML(true);

    $mail->Subject = "Password recovery";
    $mail->Body = "<h3>Password recovery<h3></br><p>Hi there, your password is '$admin'</p>";

    if(!$mail->send()) {
        echo json_encode(array(
                                "errno" => 0,
                                "message" => "Email not sent.",
                                )
                        );

    } else {
        echo json_encode(array(
                                "errno" => 0,
                                "message" => "Email sent.",
                                )
                        );
    }

} catch(PDOException $e) {

    echo json_encode(array(
                            "errno" => 1,
                            "feedback" => $e->getMessage(),
                            "message" => "Error occured",
                            )
                    );  
}

}
);

好的,所以我有这个代码来检索密码并直接发送到邮件,它工作得很好,我收到邮件,但唯一的问题是我得到密码为&#39;数组&#39;。密码是$ admin。有帮助吗?提前致谢

1 个答案:

答案 0 :(得分:1)

使用$stmt->fetch(PDO::FETCH_ASSOC);,您会获得一行(在本例中为第一行),而不是列值 获取应使用的列值

 $row = $stmt->fetch(PDO::FETCH_ASSOC);
 $admin =  $row['admin_password'];

如果你重新调整一个以上的值,你就会在查询结果上循环