How to insert, update, and delete data

Properties of the mysqli class for checking the result

Property Description
affected_rows Returns the number of affected rows. If no rows were affected, this property returns zero.
insert_id Returns the auto generated ID used in the last query. If no ID was generated, this property returns zero.
error Returns the error message if an error occurred. Otherwise, it returns an empty string.
errno Returns the error number if an error occurred. Otherwise, it returns zero.

How to execute an INSERT statement

// Escape the parameters 
$category_id_esc = $db->escape_string($category_id); 
$code_esc = $db->escape_string($code); 
$name_esc = $db->escape_string($name); 
$price_esc = $db->escape_string($price); 
// Execute the statement 
$query = "INSERT INTO products (categoryID, productCode, productName, listPrice) 
                VALUES ('$category_id_esc', '$code_esc', '$name_esc', '$price_esc')";
$success = $db->query($query); 
// Check the result
if ($success) { 
  $count = $db->affected_rows; 
  echo("<p>$count product(s) were added.</p>");
  // Get the product ID that was automatically generated 
  $product_id = $db->insert_id; 
  echo("<p>Generated product ID: $product_id.</p>");
} else { 
  $error_message = $db->error; 
  echo("<p>An error occurred: $error_message.</p>");
}
    

Back