How to select data

A method of the mysqli class for returning a result set

Method Description
query($select_statement) Executes the specified SELECT statement and returns a mysqli object for the result set. If no re-sult set is returned, this method returns a FALSE value.
real_escape_string($string) Escapes special characters in the specified string and returns the new string.
escape_string($string) Same as the real_escape_string method.

A property and a method of the mysqli_resultset class

Property/Method Description
num_rows The number of rows in the result set.
fetch_assoc() Returns the result set as an associative array.

How to execute a SELECT statement

// Escape the parameters
$category_id_esc = $db->escape_string($category_id); 
// Execute the statement - manually add single quotes around parameters 
$query = "SELECT * FROM products WHERE categoryID = '$category_id_esc'";
$result = $db->query($query); 
// Check the result set 
if ($result == false) { 
  $error_message = $db->error; 
  echo("An error occurred: $error_message");
  exit;
} 
// Get the number of rows in the result set 
$row_count = $result->num_rows;

How to display the results

<?php 
for ($i = 0; $i < $row_count; $i++) : 
  $product = $result->fetch_assoc(); 
?>
<tr>
  <td><?php echo $product['productID']; ?></td>
  <td><?php echo $product['categoryID']; ?></td>
  <td><?php echo $product['productName']; ?></td>
  <td><?php echo $product['productCode']; ?></td>
  <td><?php echo $product['listPrice']; ?></td>
</tr>

How to free resources used by the result set and database connection

// close the result set
 $result->free();
 // close the db connection
 $db->close();

Back