Rob Alford Rob Alford - 2 months ago 4x
MySQL Question

PHP mysqli_query won't execute

I'm trying to write my first basic PHP RESTful API - I managed to get it working on my local machine using MAMP. But when I uploaded to hosting server, it doesn't want to work.

Code below - I've added some ECHO's in there to make sure things are working along the way. It seems like we're all good up until the




// Connect to db
$con = mysqli_connect("HOSTNAME","USER","PASSWORD","DATABASE");

echo "Database: ";
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
echo "Connected successfully";
echo "<br><br>";

// Get value from url
$bid = $_GET['bid'];
echo "BID: ";
echo $bid;
echo "<br><br>";

// Define Query
$sql = "SELECT id, bandname, members, bio, songlist FROM bands WHERE id='$bid'";
echo "SQL Query: ";
echo $sql;
echo "<br><br>";

// Run Query
$result = mysqli_query($con, $sql);
echo "Result: ";
echo "<br><br>";

// Put Query result into array
$result_array = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo "Result Array: ";
echo "<br><br>";

// Encode array as JSON and output
echo "JSON: ";
echo json_encode($result_array);


The url I'm entering is and this is the output I'm getting in the browser...

Database: Connected successfully

BID: 1

SQL Query: SELECT id, bandname, members, bio, songlist FROM bands WHERE id='1'


Result Array:

JSON: null

When I manually run the query
SELECT id, bandname, members, bio, songlist FROM bands WHERE id='1'
in the database (PHPmyadmin), it works fine and I get 1 row returned with the correct values.

The manual db query result:
enter image description here


Any help would be most appreciated!!


OK, i think i found the issue... My "successfully Connected" wasn't written correctly, and always came back looking good. It looks like after fixing that, i have db connection issues.

I'm going to go look up the db connection settings and try and fix that.

Thanks all for your help!


Your all code is correct, I have tested in my local just change your HOSTNAME like "localhost", USER like "root", PASSWORD like "your password", DATABASE like "YOUR DATABASE NAME".

$con = mysqli_connect("HOSTNAME","USER","PASSWORD","DATABASE");

please, visit