0

I created the database "publications" in mysql and established a connection to it in PHP but could not access it. And I got the error message: "Database access failed" as I wrote in the end of the code. Here is the code from PHP:

<?php
  require_once 'login.php';
  $conn = new mysqli($hn, $un, $pw, $db);
  if($conn->connect_error) die("Fatal Error");

  $query = "CREATE TABLE cats(
   id SMALLINT NOT NULL AUTO_INCREMENT, 
   family VARCHAR(32) NOT NULL, 
   name VARCHAR(32) NOT NULL, 
   age TINYINT NOT NULL, 
   PRIMARY KEY(id)
  )";

  $result = $conn->query($query);
  if(!$result) die("Database access failed");  //I am stuck here

?>
Qingqing
  • 11
  • 3
  • 2
    Can you change `if(!$result) die("Database access failed");` with `if(!$result) die($conn->error);` to get the actual database error ? – Clément Baconnier Apr 30 '20 at 07:03
  • Better still, get mysqli to throw an exception when an error occurs, and then get PHP to log it. That way you don't have to litter your code with verbose and distracting `if` statements every time you run a query. See these guides to help you set it up: https://stackify.com/php-error-logs-guide/ (php error logging/reporting) https://stackoverflow.com/a/14578644/5947043 (mysqli exception handling) – ADyson Apr 30 '20 at 07:13
  • 1
    I changed the code and got a message The table cats already exists. I don't remember that. Thanks a lot for help:) – Qingqing Apr 30 '20 at 07:20

0 Answers0