I'm very befuddled as to why my sql query is returning null because it literally was just returning the correct object before and I feel that I didn't change the query code.
I know my database is working b/c other parts of my website use the $mysqli
created in configsql.php
and they're still up. I even ran the query on SELECT * FROM Album WHERE id = 2
on my MAMP database and it returns me the correct value! So I don't understand why my sql query in my code is returning null.
If anyone would help me w/ this that would be greatly appreciated!
$result = $stmt->get_result(); //returns null
if($row = $result->fetch_assoc() && $result->num_rows === 1){ //which causes $row to be null
Code
Basically what I'm doing is I have an AJAX request that sends information to sqlinfo.php
which calls the sql database on MAMP and is suppose to return the information on the database on the $info
array, which is then printed on the console in the main.js
. And for some reason, $info
array always has null elements :(
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);
?>