我非常迷惑为什么我的sql查询返回null,因为它之前只是返回正确的对象,我觉得我没有更改查询代码。
我知道我的数据库正在运行b / c我网站的其他部分使用$mysqli
中创建的configsql.php
,他们仍然处于启动状态。我甚至在我的MAMP数据库上的SELECT * FROM Album WHERE id = 2
上运行查询,它返回正确的值!所以我不明白为什么我的代码中的sql查询返回null。
如果有人愿意帮助我,我将不胜感激!
$result = $stmt->get_result(); //returns null
if($row = $result->fetch_assoc() && $result->num_rows === 1){ //which causes $row to be null
基本上我正在做的是我有一个AJAX请求,它向sqlinfo.php
发送信息,该请求调用MAMP上的sql数据库,并假设在$info
上返回数据库上的信息。数组,然后打印在main.js
的控制台上。由于某种原因,$info
数组始终具有空元素:(
main.js
$(document).ready(function () {
$(".grid").on("click", ".edit", function (){
var albumId = $(this).siblings(".grid-info").attr("id");
var imageId = $(this).siblings("img").attr("id");
var request = (albumId != '') ? {requestType: 'Album', id: albumId} : {requestType: 'Image', id: imageId};
var getSQLInfo = $.ajax({
url: '../P3_M2/ajax/sqlinfo.php',
method: 'POST',
data: request,
dataType: 'json',
error: function(error) {
console.log(error);
}
});
getSQLInfo.success(function (sqlInfo){
console.log(sqlInfo); //every element in info array is nulll
});
});
});
configsql.php
<?php
define( 'DB_HOST', 'correct');
define('DB_NAME', 'correct');
define('DB_USER', 'correct');
define('DB_PASS','correct');
//Set up sqli
$mysqli = new mysqli( DB_HOST, DB_USER, DB_PASS, DB_NAME );
if ($mysqli->errno) { //Was there an error connecting to the database?
//The page isn't worth much without a db connection so display the error and quit
print($mysqli->error);
exit();
}
?>
sqlinfo.php
<?php
require_once('../configsql.php');
$queryFor = array(
'Album' => 'SELECT * FROM Album WHERE id = ?',
'Image' => 'SELECT * FROM Image WHERE id = ?');
$requestType = filter_input(INPUT_POST, 'requestType', FILTER_SANITIZE_STRING);
if (empty($requestType)) {
echo 'Missing requestType.';
die();
}
$id = $mysqli->real_escape_string($_POST["id"]);
$info= array();
$stmt = $mysqli->prepare($queryFor[$requestType]);
$stmt->bind_param('i', $id);
$executed = $stmt->execute();
if(!$executed){
echo "SQL query $queryFor[$requestType] not executed";
exit();
}
$result = $stmt->get_result();
$stmt->close();
if($row = $result->fetch_assoc() && $result->num_rows === 1){
$info['id'] = $row['id'];
$info['title'] = $row['title'];
$info['date_created'] = $row['date_created'];
$info['creator'] = $row['creator'];
}
// Send back the array as json
echo json_encode($info);
&GT;