如何从Prepared语句中获取行数据,然后将其与AJAX()函数一起使用

时间:2017-06-04 22:53:49

标签: php mysql ajax mysqli prepared-statement

使用Mysqli我的代码工作正常,但是当我尝试使用预准备语句时,为了更安全,我无法将值返回到我的AJAX()函数。

这是我的js代码

function validateCoSigner(){
var contractNo = $('#cosigner_reference_number').val();
var firstName = $('#cosigner_firstname').val();
var lastName = $('#cosigner_lastname').val();
$.ajax({
    type: 'POST',
    url: 'php/retrieve-applicant1-details.php',
    // dataType: 'json',
    data: {
        'contractNo': contractNo,
        'firstName' : firstName,
        'lastName'  : lastName
    }, 
    success: function(json) {
        showCoSigner();
        console.log(json);
        $('#contractID').val(json.contractID);
        $('#loanpurpose').val(json.loanpurpose);
        $('#applicant1_firstname').val(json.applicant1_firstname);
        $('#applicant1_middlename').val(json.applicant1_middlename);        
        $('#applicant1_surname').val(json.applicant1_surname);
        $('#applicant1_dateofbirth').val(json.applicant1_dateofbirth);
    }, 
    error: function() {
        alert ('error2');

    }
});

}

这是具有mysqli功能的retrieve-applicant1-details.php文件:

<?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost", "root","","xxx");

$contractno = $_POST['contractNo'];
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];

$sql = "SELECT * FROM contract WHERE contractID='$contractno' AND applicant1_firstname='$firstname' AND applicant1_surname='$lastname'";
$query = mysqli_query($conn,$sql);
$num_row = mysqli_num_rows($query);
$row=mysqli_fetch_assoc($query);
if( $num_row == 1 ) {
    $obj = [
        'contractID'                =>($row['contractID']), 
        'loanpurpose'               =>($row['loanpurpose']), 
        'applicant1_firstname'      =>($row['applicant1_firstname']), 
        'applicant1_middlename'     =>($row['applicant1_middlename']), 
        'applicant1_surname'        =>($row['applicant1_surname']), 
        'applicant1_dateofbirth'    =>($row['applicant1_dateofbirth']), 
    ];
    }
else {
    echo 'The reference number, firstname and lastname does not match';
    exit;
}

echo json_encode($obj);
?>

如果我使用如下的预处理语句,我无法弄清楚如何正确获取数据,以便我可以将值返回到我的Ajax函数,以便它可以以我的形式显示。

<?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost", "root","","xxx");

$contractno = $_POST['contractNo'];  //not sure if I still need to use mysqli_real_escape_string here.
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];

// prepare statement        
$stmt = $conn->prepare("SELECT * FROM contract WHERE contractID=? AND applicant1_firstname=? AND applicant1_surname=?");
// bind
$stmt->bind_param("iss", $contractno, $firstname, $lastname);
// execute
$stmt->execute();
if ($stmt->errno) {
    echo "FAILURE!!! " . $stmt->error;
}
else echo "Updated {$stmt->affected_rows} rows";

$row = $stmt->fetchObject();
$obj = (
    'contractID'                =>($row['contractID']), 
    'loanpurpose'               =>($row['loanpurpose']), 
    'applicant1_firstname'      =>($row['applicant1_firstname']), 
    'applicant1_middlename'     =>($row['applicant1_middlename']), 
    'applicant1_surname'        =>($row['applicant1_surname']), 
    'applicant1_dateofbirth'    =>($row['applicant1_dateofbirth']), 
);

echo json_encode($obj);
?>

我是新手。任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:2)

在MySQLi中准备语句时,您需要使用bind_result()将结果列绑定到变量中,您将使用这些变量而不是您使用的$row数组。你没有准备好声明(就像你使用mysqli_fetch_*()函数一样)。

重要的是,您绑定的变量数量与所选列的数量相匹配。这就是为什么我修改了你的查询,以匹配它。

然后你需要fetch()结果。实施这些更改后,您的查询应该看起来像这样

$stmt = $conn->prepare("SELECT contractID, 
                               loanpurpose, 
                               applicant1_firstname, 
                               applicant1_middlename, 
                               applicant1_surname, 
                               applicant1_dateofbirth 
                        FROM contract 
                        WHERE contractID=? 
                          AND applicant1_firstname=? 
                          AND applicant1_surname=?");
$stmt->bind_param("iss", $contractno, $firstname, $lastname);
$stmt->execute();
$stmt->bind_result($contractID, $loanpurpose, $applicant1_firstname, $applicant1_middlename, $applicant1_surname, $applicant1_dateofbirth);
if ($stmt->errno) {
    die("Query failed to execute: " . $stmt->error);
}
if ($stmt->fetch()) {
    echo json_encode(array("contractID" => $contractID, 
                           "loanpurpose" => $loanpurpose,  
                           "applicant1_firstname" => $applicant1_firstname,  
                           "applicant1_middlename" => $applicant1_middlename,  
                           "applicant1_surname" => $applicant1_surname,  
                           "applicant1_dateofbirth" => $applicant1_dateofbirth));
} else {
    echo "No matching rows returned.";
}
$stmt->close();

不,你不应该在使用准备好的声明时使用mysqli_real_escape_string() - 通过转义不需要转义的引号(IF I use mysqli prepared statements do i need to escape)来破坏数据。

您可以检查$stmt->num_rows == 1是否返回true,而不是使用$stmt->fetch(),因为您只需要一行,您不需要检查金额 - 只需某事< / em>被抓了。根据手册,$stmt->fetch()会返回true表示成功查询,null如果没有返回任何行。
这种方法可能更好的原因是因为您可以避免在使用$stmt->store_result();之前调用$stmt->num_rows;。这在资源方面更有效,但也节省了一些打字; - )

另请注意,echo "Updated {$stmt->affected_rows} rows";在此处使用是没有意义的,因为您正在运行SELECT查询,而不是UPDATE查询。如果要查看返回的行数,可以使用$stmt->num_rows;代替。