PHP functions for MySql : mysqli_query()

The mysqli_query() function is used to execute SQL queries against the MySQL database server. It returns true on success for SELECT, SHOW, DESCRIBE OR EXPLAIN queries or false on failure. The syntax is :
mysqli_query(connection, query, resultmode);
Where :
  • connection specifies the connection to use.
  • query specifies the query string to execute on database.
  • resultmode is optional argument, the possible values are MYSQLI_USE_RESULT (used when you have to retrieve large amount of data from the database) and MYSQLI_STORE_RESULT (default option).
Example :
<?php

  $server = "localhost";
  $username = "root";
  $password = "";
  $dbName = "mydb";

  $connection = mysqli_connect($server, $username, $password, $dbName);

  if(!$connection) {
    die("Connection failed: " . mysqli_connect_error());
  } else {
    echo "Successfully connected to MySQL database.";
  }

  mysqli_query($connection, "SELECT * from employee");

  mysqli_query($connection, "INSERT INTO employee VALUES(106, 'Jack', 2000, 'Russia', 123456)");

  mysqli_close($connection);

?>
We can also add error checking routine into the mysqli_query() function. For example :
<?php

  $server = "localhost";
  $username = "root";
  $password = "";
  $dbName = "mydb";

  $connection = mysqli_connect($server, $username, $password, $dbName);

  if(!$connection) {
    die("Connection failed: " . mysqli_connect_error());
  } else {
    echo "Successfully connected to MySQL database.";
  }

  $sql = "SELECT * from employee";

  if(mysqli_query($connection, $sql)) {
    echo "<br/>Query Executed Successfully.";
  } else {
    echo "Error in Executing query : " . mysqli_error($conn);
  }

  $sql = "INSERT INTO employee VALUES(106, 'Jack', 2000, 'Russia', 123456)";

  if(mysqli_query($connection, $sql)) {
    echo "<br/>New Row Added Successfully.";
  } else {
    echo "<br/>Error in Executing query : " . mysqli_error($conn);
  }

  mysqli_close($connection);

?>
Output :

Successfully connected to MySQL database.
Query Executed Successfully.
New Row Added Successfully.


Next Topic :