How to Send an SQL Server to the MySQL Server

After you have an open connection to the MySQL server, you send your SQL statement query. To interact with the database, put your SQL statement into a variable and send it to the MySQL server with the function mysqli_query, as in the following example:

$query = "SELECT * FROM Customer";
$result = mysqli_query($cxn,$query)
              or die ("Couldn't execute query.");

The query is executed on the currently selected database for the specified connection.

The variable $result holds information on the result of executing the query but not the actual results. The information in $result depends on whether or not the query gets information from the database:

  • For queries or statements that don’t get any data: The variable $result contains information about whether the query or statement executed successfully or not. If it’s successful, $result is set to true; if it’s not successful, $result is set to false. Some queries and statements that don’t return data are INSERT and UPDATE.

  • For queries that return data: The variable $result contains a result identifier that specifies where the returned data is located, not the returned data itself. Some queries that return data are SELECT and SHOW.

The use of single and double quotes can be a little confusing when assigning the query or statement to the $query variable. You’re actually using quotes on two levels: the quotes that assign the string to $query and the quotes that are part of the SQL language itself.

The following guidelines can help you avoid any problems with quotes when working with SQL:

  • Use double quotes at the beginning and end of the string.

  • Use single quotes before and after variable names.

  • Use single quotes before and after literal values.

The following statements show examples of assigning SQL strings to variables in PHP:

$query = "SELECT firstName FROM Customer";
$query = "SELECT firstName FROM Customer WHERE lastName='Smith'";
$query = "UPDATE Customer SET lastName='$last_name'";

The SQL statement itself doesn’t include a semicolon (;), so don’t put a semicolon inside the final quote. The only semicolon appears at the very end; this is the PHP semicolon that ends the statement.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.