0

I need to access a database remotely using PHP and display the fetched data in html. My code is as below

$servername = "192.168.56.1:3306";
$username = "root";
$password = "";
$dbname = "grh";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  error_log("Failed to connect to database!", 0);
  die("Connection failed: " . $conn->connect_error); 
}

$sql = "SELECT * FROM ip_patient_logs";
$result = $conn->query($sql);
$rows = array();

if ($result->num_rows > 0) {
    while($r = mysqli_fetch_assoc($result)) {
        $rows[] = $r;
    }
    print json_encode($rows);
} else {
  echo "0 results";
}
$conn->close();

I expected to be able to connect to the database and fetch the data , but it displays blank page. I am a beginner in PHP.

ss2022
  • 1
  • 1
  • Have you check the error log? Or [display error messages](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display). Oh, and PHP pages start with ` – KIKO Software Oct 27 '22 at 09:16
  • have you tried using echo json_encode($rows) instead or print? – Nicolas Tome Oct 27 '22 at 09:18
  • Enable error reporting: add `ini_set('display_errors', 1); ini_set('log_errors',1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` to the top of your script. This will force any `mysqli` errors to generate an Exception that you can see on the browser as well as normal PHP errors. – ADyson Oct 27 '22 at 10:49
  • @Nicolas Tome yes tried with echo, but same issue – ss2022 Oct 28 '22 at 08:38
  • @ KIKO Software yes – ss2022 Oct 28 '22 at 08:40
  • You are using `print json_encode` in part of your code and `echo` in other parts, Are you using JS fetch or any other async technique? If the final query result is used in JS you should use `echo json_encode("x results")` – Nicolas Tome Oct 28 '22 at 09:15

0 Answers0