Mysqli

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 17

Using PHP’s MySQLi Extension

<?php
$mysqli = new mysqli("localhost", "user", "pass", "music");
if ($mysqli === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT artist_id, artist_name FROM artists";

Retrieving Data if ($result = $mysqli->query($sql)) {


if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
echo $row[0] . ":" . $row[1] . "\n";
}
$result->close();
} else {
echo "No records matching your query were found.";
}
} else {
echo "ERROR: Could not execute $sql. " . $mysqli->error;
}
$mysqli->close();
?>
• In order to begin communication with the MySQL database server,
you first need to open a connection to the server.
• All communication between PHP and the database server takes
place through this connection.
• In order to initialize this connection, initialize an instance of the
MySQLi class and pass the object constructor four arguments: the
host name of the MySQL server to connect to, a valid username and
password to gain access to it, and the name of the database to use.
• Assuming the connection attempt is successful, this object instance
represents the database connection for all future operations and
exposes methods for querying,fetching, and processing result sets.
• If the connection attempt is unsuccessful, the object instance will
become false; an error message explaining the reason for failure can
now be obtained by calling the mysqli_connect_error() function.
• The next step is to create and execute the SQL query.
• This is accomplished by calling the MySQLi object’s
query() method and passing it the query to be executed.
• If the query was unsuccessful, the method returns Boolean
false, and an error message explaining the cause of failure
is stored in the MySQLi object’s 'error' property.
• If, on the other hand, the query is successful and returns one or more records,
the return value of the query() method is another object, this one an instance
of the MySQLi_Result class.
• This object represents the result set returned by the query, and it exposes
various methods for processing the individual records in the result set.
• One such method is the fetch_array() method.
• Each time fetch_array() is invoked, it returns the next record in the result set
as an array.
• This makes the fetch_array() method very suitable for use in a while or for
loop.
• The loop counter determines how many times the loop should run; this value
is obtained from the MySQLi_Result object’s 'num_rows' property, which
stores the number of rows returned by the query.
• Individual fields from the record can be accessed as array elements, using
either the field index or the field name
The 'num_rows' property is only meaningful when used with
queries that return data, such as SELECT queries; it shouldn’t
be used with INSERT, UPDATE, or DELETE queries.

• Each result set returned after a query occupies some


amount of memory.
• Thus, once the result set has been processed, it’s a good
idea to destroy the MySQLi_Result object, and free up the
used memory, by calling the object’s close() method.
• And once you’ve completed working with the database,
it’s also a good idea to destroy the main MySQLi object in
a similar manner, by calling its close() method
Returning Records as Arrays and Objects
• This method returns each record from the result set as an
array containing both numerically indexed and string-indexed
keys; this allows developers the convenience of referring to
individual fields of each record either by index or by field name
<?php
$mysqli = new mysqli("localhost", "user", "pass", "music");
if ($mysqli === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT artist_id, artist_name FROM artists";
if ($result = $mysqli->query($sql)) {
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
echo $row['artist_id'] . ":" . $row['artist_name'] . "\n";
}
$result->close();
} else {
echo "No records matching your query were found.";
}
} else {
echo "ERROR: Could not execute $sql. " . $mysqli->error;
}
$mysqli->close();
?>
• However, there’s also a third way of retrieving records: as objects,
using the fetch_object() method.
• Here, each record is represented as an object, and the fields of a
record are represented as object properties.
• Individual fields can then be accessed using standard $object-
>property notation.
<?php
$mysqli = new mysqli("localhost", "user", "pass", "music");
if ($mysqli === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT artist_id, artist_name FROM artists";
if ($result = $mysqli->query($sql)) {
if ($result->num_rows > 0) {
while($row = $result->fetch_object()) {
echo $row->artist_id . ":" . $row->artist_name . "\n";
}
$result->close();
} else {
echo "No records matching your query were found.";
}
} else {
echo "ERROR: Could not execute $sql. " . $mysqli->error;
}
$mysqli->close();
?>
Adding or Modifying Data
<?php
$mysqli = new mysqli("localhost", "user", "pass", "music");
if ($mysqli === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO artists (artist_name, artist_country) VALUES
('Kylie Minogue', 'AU')";
if ($mysqli->query($sql) === true) {
echo 'New artist with id:' . $mysqli->insert_id . ' added.';
} else {
echo "ERROR: Could not execute query: $sql. " . $mysqli->error;
}
$mysqli->close();
?>
<?php
$mysqli = new mysqli("localhost", "user", "pass", "music");
if ($mysqli === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "UPDATE artists SET artist_name = 'Eminem', artist_country = 'US' WHERE
artist_id = 7";
if ($mysqli->query($sql) === true) {
echo $mysqli->affected_rows . ' row(s) updated.';
} else {
echo "ERROR: Could not execute query: $sql. " . $mysqli->error;
}
$mysqli->close();
?>
Using Prepared Statements
• In the event that you need to execute a particular query
multiple times with different values—for example, a series
of INSERT statements—the MySQL database server
supports prepared statements, which offer a more
efficient means of accomplishing this task than repeatedly
calling the $mysqli->query() method.
<?php
$songs = array(
array('Patience', 4, 3),
array('Beautiful World', 4, 4),
array('Shine', 4, 4),
array('Hold On', 4, 3),
);
$mysqli = new mysqli("localhost", "user", "pass", "music");
if ($mysqli === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO songs (song_title, fk_song_artist, fk_song_rating)VALUES (?, ?, ?)";
if ($stmt = $mysqli->prepare($sql)) {
foreach ($songs as $s) {
$stmt->bind_param('sii', $s[0], $s[1], $s[2]);
if ($stmt->execute()) {
echo "New song with id: " . $mysqli->insert_id . " added.\n";
} else {
echo "ERROR: Could not execute query: $sql. " . $mysqli->error;
} }} else {
echo "ERROR: Could not prepare query: $sql. " . $mysqli->error;
}
$mysqli->close();
?>
1. Bind the values to the prepared statement. The values to
be interpolated into the statement must be bound to their
placeholders with the MySQLi_Stmt object’s bind_param()
method. The first argument to this method must be an
ordered string sequence indicating the data types of the
values to be interpolated (s for string, i for integer, d for
double-precision number); this argument is then followed
by the actual values. In the preceding listing, the string 'sii'
indicates that the values to be interpolated into the
prepared statement will be, in sequence, a string type (the
song title), an integer type (the artist foreign key), and an
integer type (the rating foreign key)
2. Execute the prepared statement. Once the values have
been bound to their placeholders, the prepared statement
is executed by calling MySQLi_Stmt object’s execute()
method. This method replaces the placeholders in the
prepared statement with actual values and executes it on
the server.
Handling Errors
● The MySQLi object’s 'error' property holds the last error
message generated by the database server.
● The MySQLi object’s 'errno' property holds the last error
code returned by the database server.
● The mysqli_connect_error() function returns the error
message generated by the last (failed) connection attempt.
● The mysqli_connect_errno() function returns the error
code generated by the last (failed) connection attempt.

You might also like