# `mysqli` Example: Connect and Query
```
  <?php
  echo "mysqli Example" . "\n";

  mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

  try {
    ~!@$mysqli = new mysqli@!~("127.0.0.1", "root", "", "universe", 4000);
    if (~!@$mysqli->connect_errno@!~) {
      die("Error connecting: " . $mysqli->connect_error);
    }
    ~!@$res = $mysqli->query@!~("SELECT id, name, mass FROM planets");
    if (!$res) {
      echo "Query failed: " . $mysqli->error;
    } else {
      while (~!@$row = $res->fetch_assoc()@!~) {
        echo $row['id'] . ' ' . $row['name'] . ' ' . $row['mass'] . "\n";
      }
    }
  } catch (Exception $e) {
    die($e->getMessage());
  }
  ?>
```
------------------------------------------------------------------------------
The program creates a new instance of `mysqli`, passing into its constructor the TiDB address, username and password, and the default database (`universe`). The program stores the mysqli object in the `$mysqli` variable.

It then inspects the `$mysqli` object's `connect_errno` property to determine if there is an error. If there is an error, the program displays the error message to the user (using the `connect_error` property of `$mysqli`) and exits.

The program queries the universe database by calling the `$mysqli` object's `query()` method, passing in the `SELECT` statement. It stores the results (an object of type `mysqli_result`) in a variable called `$res`.

Then, it checks to see if the `$res` object contains any results. If not, it uses the `$mysqli->error` property to report failure and then exits.

Then, the program uses the `mysqli_result` object stored in `$res` and calls its `fetch_assoc()` method to retrieve a row as an associative array. The while loop fetches rows one at a time until every row has been read (that is, `$row` no longer evaluates to true.)

Last, the program uses column names to look up the values within the associative array that represents the row and display them to the user.

Example:
```
<html>

<body>
  <h1>201.4-PHP Connection 09</h1>
  <?php
  echo "mysqli Example - Connect and Query" . "<p>";

  mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

  try {
    $mysqli = new mysqli("127.0.0.1", "root", "", "universe", 4000);
    if ($mysqli->connect_errno) {
      die("Error connecting: " . $mysqli->connect_error);
    }
    $res = $mysqli->query("SELECT id, name, mass FROM planets");
    if (!$res) {
      echo "Query failed: " . $mysqli->error;
    } else {
      while ($row = $res->fetch_assoc()) {
        echo $row['id'] . ' ' . $row['name'] . ' ' . $row['mass'] . "<p>";
      }
    }
    print "End.";
  } catch (Exception $e) {
    die($e->getMessage());
  }
  ?>

</body>

</html>
```