I'm building a simple PHP webservice/webapp that when queried from an external application will return JSON formatted/encoded data from a MySQL database.
The PHP webapp and MySQL database are on Bluemix (and MUST to stay there).
Here is my current code for a typical PHP page:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Before Outside of php</p>
<?php
/*
* Following code will list all the customers
*/
echo "<p>Before Inside of php</p>";
$server = "Server";
$username = "username";
$password = "password";
$database = "database";
echo "<p>1 Inside of php</p>";
// Connecting to mysql database
$mysqli = new mysqli_connect($server, $username, $password, $database);
echo "<p>2 Inside of php</p>";
$response = array();
echo "<p>3 Inside of php</p>";
if ($result = $mysqli->query("SELECT firstName, lastName FROM customer")) {
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
$response[] = $row;
}
echo json_encode($response);
}
echo "<p>4 Inside of php</p>";
$result->close();
$mysqli->close();
echo "<p>After Inside of php</p>";
?>
<p>Before Outside of php</p>
</body>
</html>
I have put in the <p>1 Inside of PHP<p>
stuff in there so I could see where the script stopped and therefore figure out why.
The last thing that gets echo'd to the screen is <p>1 Inside of php</p>
so therefore we can assume it's the MySQLi functions not working.
After some googling, I found that the main reason for this was that the MySQLi extension hasn't been included in the installation/build of the PHP webapp.
I am using this buildpack:
https://github.com/cloudfoundry/php-buildpack.git
which allows for use of a .bp-config/options.json file to include any extensions not included in the build pack.
As MySQLi is not included in the buildpack. My .bp-config/options.json
file shows as follows:
{
"PHP_EXTENSIONS": ["mysqli"]
}
Now that MySQLi is included, I threw a phpinfo();
in my PHP before the MySQLi function, just to double check, and it displayed all the PHP information WITH a section titled: MySQLi.
Just to point out, the MySQLi section wasn't there before I wrote the .bp-config/options.json
file.
However, the script STILL stops at the first MySQLi function and won't display anything after that. I'm stumped. Is it Bluemix's fault? Is it my PHP? Do I need to do something else before MySQLi is properly installed? I don't know, Help?
Your PHP is a little wrong on the line with
mysqli_connect
.It should be
$mysqli = mysqli_connect($server, $username, $password, $database);
. Notice the reference to new is not used.mysqli_connect
is a function, not a class. What you want is either:or
Both are equivalent.
Additionally the use of
MYSQL_ASSOC
should beMYSQLI_ASSOC
. Here is a full replacement of your code below.