stackEr stackEr -5 years ago 96
SQL Question

mysql query doesn't work together with cross domain in ajax

my problem is the following...
I made some php code that reads records from a mysql database:

$host = $_SESSION['host'];
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$db = $_SESSION['db'];

$con = mysqli_connect($host,$username,$password,$db);

$sql = "SELECT * FROM `table`";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {

my html:

<button onclick="list">submit</button>
<div id="output"></div>

var thisHost = "host.php";
function list() {
type: 'POST',
url: thisHost,
data: "list=true",
success: function(data)
error: function (responseData, textStatus, errorThrown)
console.warn(responseData, textStatus, errorThrown);

as far as that everything is working fine. However now i want to call the php code from another host. Therefor the html file is on the other host (localhost:81) and the php file stays on the old host (localhost:80).

now I noticed that i need a something to cross the domain because ajax doesn't seem to work with other hosts. So all i did was adding these lines to the php code right at the beginning:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');

and change the value of the thisHost var in javascript to


after that the ajax part works again and the php response. However every time i want to make a query by doing something like this:

$sql = "SELECT * FROM `table`";

i will get this error:

Fatal error: Uncaught Error: Call to a member function query() on null
in C:\path\to\host.php:71 Stack trace: #0 {main} thrown in
C:\path\to\host.php on line 71

i'm pretty sure that the query is correct. So what do i need to change?

Answer Source

Calling a method on an invalid handle will produce errors like this. Always check that your connection request succeeded and handle any errors that could have occurred.

Turning on mysqli exceptions makes these things a lot harder to ignore.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download