PHP script not returning query, but the MySql query works

Sunday, May 4, 2014

My ultimate goal is to have a js script return the results of a PHP query as json so I can do nefarious things with it.

I have the MySql query I want to use and it is definitely working when I test it in Workbench, but when I try it in the PHP script, nothing gets returned. The current query in PHP is just a placeholder one to test out the data interchange.

I manually put in something to the array (searchResults) and that gets return but NOTHING comes from the PHP script when it is executed.

// Include your database creds and login to the db
require_once 'login_karavites.php';
$db = mysqli_connect($db_hostname, $db_username, $db_password);

// Handle the input/request.
$searchString_UNSAFE = $_POST['eName']; // change that, obviously

// Bare minimum sanitation to prevent injection.
$searchString = $db->escape_string($searchString_UNSAFE);

// Construct the SQL query
$sql = "SELECT * FROM `Halls` WHERE hall_name = 'Rose Ballroom'";

// Do the database lookup.
$result = $db->query($sql);

// Create empty array to hold our results (to be sent back to the browser).
$searchResults = array();
// If we had results, put them into that array
if ($result->num_rows > 0) {

// This loop will retrieve every row from that result set
while ($row = $result->fetch_assoc()) {

// From each row, just take the 'event_name' field.
$searchResults[] = $row['hall_name'];



// Done with the db, now we just have to send the results back to the browser.

// Send the correct content-type header.
// This ensures that jQuery automatically converts the response into an
// array or object, rather than just treating it like a block of text.
// Must be the FIRST thing the PHP script outputs, or it will choke.
header('Content-type: application/json');

// Output the data.
echo json_encode($searchResults);


The js script.

$(document).ready(function() {
// All this stuff runs as soon as the page is fully loaded

// Attach a function to the Submit action on #eventForm
$('#eventForm').submit(function() {

// Submit the form via AJAX

// Attach a function to the "the PHP script returned some results" event
success: function(response, status, xhr, $form){
// I am assuming that this is your data format, for example:
// { "searchResults": [ "result1", "result2", "result3" ] }
// I am also assuming that you want your results in div#results
$('div#results').html(""); // Clear it out of anything that's already there.
for (i in response['searchResults']) {
$('div#results').append( response['searchResults'][i] );

// Give up if PHP doesn't answer in 3 seconds
timeout: 3000,

// Path to the PHP file we want to send this to
url: 'phpdata/eventsData.php'

// Make sure the browser does NOT proceed to submit the form again,
// the old fashioned way (full page reload).
return false;