0

I've problem with mysql. I've PHP script, which returned array into json data from datebase. I've message from 'echo' about successfully connection, but my result is equals which null of array.

In result on Explorer I've:

Connected successfully

query: SELECT name,id FROM rz_DWzZ'

result: 

RESULT:[]

This is this script.

$conn = mysql_connect($servername, $username, $password);
        mysql_select_db($database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
$return_arr = array();
$qstring = "SELECT name,id FROM rz_DWzZ";
$result = mysql_query($qstring,$conn);
echo "<br>query: ".$qstring."<br>";
echo "<br>result: ".$result."<br>";
while ($row = mysql_fetch_assoc($result))//loop through the retrieved values
{
        $row['name']=htmlentities(stripslashes($row['name']));
        $row['id']=(int)$row['id'];
        array_push($return_arr,$row);
}
mysql_close($conn); 
echo "<br>RESULT:".json_encode($return_arr); 
halfer
  • 19,824
  • 17
  • 99
  • 186
Remi
  • 19
  • 6

1 Answers1

1

You didn't check for failure properly. mysql_*() functions return boolean FALSE on failure, which echo will print as a zero-length/invisible string.

You have to explicitly test for it:

$result = mysql_query(...) or die(mysql_error());
                          ^^^^^^^^^^^^^^^^^^^^^^--method #1

if ($result === false) { // method #2
   die(mysql_error());
}

And of course, you should NOT be using those functions anyways. They're obsolete/deprecated, and your code is now useless in newer versions of PHP. You should be using mysqli or PDO for any new development.

As well, you have numerous other bugs:

if ($conn->connect_error) {

the mysql_*() function library has NEVER been object-oriented. It's purely procedural, and has absolutely NO object support whatsoever. Therefore this connection test will always fail, as $conn->connect_error will always evaluate to null, which converts to boolean false as well, meaning you get a false positive for success.

Marc B
  • 356,200
  • 43
  • 426
  • 500