0% found this document useful (0 votes)
21 views

Unit 4

Very good morning information

Uploaded by

rushitv382
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Unit 4

Very good morning information

Uploaded by

rushitv382
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

MANIPULATING MYSQL

DATABASES WITH PHP


OBJECTIVES
Connect to MySQL from PHP
Work with MySQL databases using PHP
Create, modify, and delete MySQL tables with PHP
Use PHP to manipulate MySQL records
Use PHP to retrieve database records

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 2


CONNECTING TO MYSQL WITH PHP
PHP has the ability to access and manipulate any database that is
ODBC compliant
PHP includes functionality that allows you to work directly with
different types of databases, without going through ODBC
PHP supports SQLite, database abstraction layer functions, and
PEAR DB

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 3


OPENING AND CLOSING A MYSQL CONNECTION
 Open a connection to a MySQL database server with the
mysqli_connect() function.
 The mysqli_connect() function returns a positive integer
if it connects to the database successfully or FALSE if it does
not.
 Assign the return value from the mysqli_connect()
function to a variable that you can use to access the database
in your script.

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 4


OPENING AND CLOSING A MYSQL
CONNECTION (CONTINUED)
The syntax for the mysqli_connect() function is:
$connection = mysqli_connect("host" [,
"user", "password"]);
 The host argument specifies the host name where your MySQL
database server is installed
 The user and password arguments specify a MySQL account name
and password

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 5


OPENING AND CLOSING A MYSQL
CONNECTION (CONTINUED)

The database connection is assigned to the $DBConnect


variable

$DBConnect = mysqli_connect("localhost",
“root", “root");

Close a database connection using the mysqli_close()


function

mysqli_close($DBConnect);

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 6


OPENING AND CLOSING A MYSQL
CONNECTION (CONTINUED)

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 7


OPENING AND CLOSING A MYSQL
CONNECTION (CONTINUED)

Figure 8-1 MySQLInfo.php in a Web browser

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 8


SELECTING A DATABASE
The syntax for the mysqli_select_db() function is:

mysqli_select_db(database [, connection]);

 The function returns a value of TRUE if it successfully selects a


database or FALSE if it does not.
 For security purposes, you may choose to use an include file to
connect to the MySQL server and select a database

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 9


REPORTING MYSQL ERRORS

Reasons for not connecting to a database server


include:
 The database server is not running

 Insufficient privileges to access the data source

 Invalid username and/or password

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 10


REPORTING MYSQL ERRORS (CONTINUED)

 The mysqli_errno() function returns the error code from


the last attempted MySQL function call or 0 if no error occurred

 The mysqli_errno() and mysqli_error() functions


return the results of the previous mysqli*() function

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 11


SUPPRESSING ERRORS WITH THE ERROR
CONTROL OPERATOR
 By default, functions in the mysql package display errors and
warnings as they occur
 Use the error control operator (@) to suppress error messages
 The error control operator can be prepended to any expression
although it is commonly used with expressions

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 12


TERMINATING SCRIPT EXECUTION
The die() and exit() functions terminate script execution
 The die() version is usually used when attempting to access a
data source
 Both functions accept a single string argument
 Call the die() and exit() functions as separate statements or by
appending either function to an expression with the Or operator

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 13


TERMINATING SCRIPT EXECUTION
(CONTINUED)
$DBConnect = @mysqli_connect("localhost", "root", "");
if (!$DBConnect)
die("<p>The database server is not available.</p>");
echo "<p>Successfully connected to the database server.</p>";

$DBSelect = @mysqli_select_db($DBConnect, "flightlog");


if (!$DBSelect)
die("<p>The database is not available.</p>");

echo "<p>Successfully opened the database.</p>";


// additional statements that access the database
mysqli_close($DBConnect);

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 14


TERMINATING SCRIPT EXECUTION
(CONTINUED)
$DBConnect = @mysqli_connect("localhost", “root", “root")

Or die("<p>The database server is not available.</p>");

echo "<p>Successfully connected to the database server.</p>";

@mysqli_select_db($DBConnect, “mydata")

Or die("<p>The database is not available.</p>");

echo "<p>Successfully opened the database.</p>";

// additional statements that access the database server

mysqli_close($DBConnect);

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 15


REPORTING MYSQL ERRORS
Table 9-2 MySQL error reporting functions

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 16


REPORTING MYSQL ERRORS (CONTINUED)

$User = $_GET['username'];
$Password = $_GET['password'];
$DBConnect = @mysqli_connect("localhost", $User, $Password)
Or die("<p>Unable to connect to the database server.</p>"
. "<p> Error code " . mysqli_connect_errno()
. ": " . mysqli_connect_error()) . "</p>";
echo "<p>Successfully connected to the database server.</p>";
@mysqli_select_db($DBConnect, "flightlog")
Or die("<p>The database is not available.</p>");
echo "<p>Successfully opened the database.</p>";
// additional statements that access the database
mysqli_close($DBConnect);

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 17


REPORTING MYSQL ERRORS (CONTINUED)

Figure 9-4 Error number and message generated by


an invalid username and password

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 18


REPORTING MYSQL ERRORS (CONTINUED)
$User = $_GET['username'];

$Password = $_GET['password'];

$DBConnect = @mysqli_connect("localhost", $User, $Password)

Or die("<p>Unable to connect to the database server.</p>"

. "<p>Error code " . mysqli_connect_errno()

. ": " . mysqli_connect_error()) . "</p>";

echo "<p>Successfully connected to the database server.</p>";

@mysqli_select_db($DBConnect, "flightplan")

Or die("<p>Unable to select the database.</p>"

. "<p>Error code " . mysqli_errno($DBConnect)

. ": " . mysqli_error($DBConnect)) . "</p>";

echo "<p>Successfully opened the database.</p>";

// additional statements that access the database

mysqli_close($DBConnect);

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 19


REPORTING MYSQL ERRORS (CONTINUED)

Figure 9-5 Error code and message generated when


attempting to select a database that does not exist

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 20


EXECUTING SQL STATEMENTS
Use the mysqli_query() function to send SQL statements to
MySQL
The syntax for the mysqli_query() function is:
mysqli_query(query [, connection]);

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 21


EXECUTING SQL STATEMENTS (CONTINUED)

The mysqli_query() function returns one of three values:


 For SQL statements that do not return results (CREATE DATABASE and
CREATE TABLE statements) it returns a value of TRUE if the statement
executes successfully.
 For SQL statements that return results (SELECT and SHOW statements) the
mysqli_query() function returns a result pointer that represents the
query results.
o A result pointer is a special type of variable that refers to the currently
selected row in a resultset.
 The mysqli_query() function returns a value of FALSE for any SQL statements
that fail, regardless of whether they return results.

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 22


WORKING WITH QUERY RESULTS

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 23


RETRIEVING RECORDS INTO AN
INDEXED ARRAY
The mysqli_fetch_row() function returns the fields in the current
row of a resultset into an indexed array and moves the result pointer to
the next row

echo "<table width='100%‘ border='1'>";


echo "<tr><th>Make</th><th>Model</th>
<th>Price</th><th>Quantity</th></tr>";
$Row = mysqli_fetch_row($QueryResult);
do {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td align='right'>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td></tr>";
$Row = mysqli_fetch_row($QueryResult);
} while ($Row);

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 24


RETRIEVING RECORDS INTO AN INDEXED
ARRAY
$SQLstring = "SELECT * FROM company_cars";
$QueryResult = @mysqli_query($SQLstring, $DBConnect);
echo "<table width='100%' border='1'>\n";
echo "<tr><th>License</th><th>Make</th><th>Model</th>
<th>Mileage</th><th>Year</th></tr>\n";
while (($Row = mysqli_fetch_row($QueryResult)) !== FALSE) {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td>";
echo "<td>{$Row[4]}</td></tr>\n";
}
echo "</table>\n";

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 25


RETRIEVING RECORDS INTO AN INDEXED
ARRAY

Figure 8-8 Output of the company_cars table in a Web Browser

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 26


RETRIEVING RECORDS INTO AN
ASSOCIATIVE ARRAY

 mysqli_fetch_assoc() function returns the fields in the


current row of a resultset into an associative array and moves the
result pointer to the next row
 The difference between mysqli_fetch_assoc() and
mysqli_fetch_row()
 Instead of returning the fields into an indexed array, the
mysqli_fetch_assoc() function returns the fields into
an associate array and uses each field name as the array
key.

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 27


ACCESSING QUERY RESULT INFORMATION

 The mysqli_num_rows() function returns the number of


rows in a query result
 The mysqli_num_fields() function returns the number
of fields in a query result
 Both functions accept a database connection variable as an
argument.

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 28


CLOSING QUERY RESULTS
 When you are finished working with query results retrieved
with the mysqli_query() function, use the
mysqli_free_result() function to close the resultset
 To close the resultset, pass to the mysqli_free_result()
function the variable containing the result pointer from the
mysqli_query() function

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 29


ADDING, DELETING, AND UPDATING
RECORDS
 To add records to a table, use the INSERT and VALUES
keywords with the mysqli_query() function
 The values entered in the VALUES list must be in the same
order in which you defined the table fields
 You must specify NULL in any fields for which you do not have
a value

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 30


ADDING, DELETING, AND UPDATING
RECORDS (CONTINUED)
 To add multiple records to a database, use the LOAD DATA
statement and the mysqli_query() function with a local
text file containing the records you want to add
 To update records in a table, use the UPDATE, SET, and
WHERE keywords with the mysqli_query() function

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 31


ADDING, DELETING, AND UPDATING
RECORDS (CONTINUED)
 The UPDATE keyword specifies the name of the table to
update
 The SET keyword specifies the value to assign to the fields in
the records that match the condition in the WHERE keyword
 To delete records in a table, use the DELETE and WHERE
keywords with the mysqli_query() function
 The WHERE keyword determines which records to delete in the
table

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 32


USING THE
MYSQL_AFFECTED_ROWS() FUNCTION
 With queries that return results (SELECT queries), use the
mysqli_num_rows() function to find the number of
records returned from the query
 With queries that modify tables but do not return results
(INSERT, UPDATE, and DELETE queries), use the
mysqli_affected_rows() function to determine the
number of affected rows

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 33


USING THE MYSQL_AFFECTED_ROWS()
FUNCTION (CONTINUED)
$SQLstring = "UPDATE company_cars SET mileage=50112.3
WHERE license='AK-1234'";
$QueryResult = @mysqli_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect) . "</p>";
else
echo "<p>Successfully updated " .
mysqli_affected_rows($DBConnect) . " record(s).</p>";

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 34


USING THE MYSQL_AFFECTED_ROWS()
FUNCTION (CONTINUED)

Figure 8-5 Output of mysqli_affected_rows() function


for an UPDATE query

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 35


USING THE MYSQL_INFO()
FUNCTION
 For queries that add or update records, or alter
a table’s structure, use the mysqli_info() function to
return information about the query
 The mysqli_info() function returns the number of
operations for various types of actions, depending on the type
of query
 The mysqli_info() function returns information about the
last query that was executed on the database connection

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 36


USING THE MYSQL_INFO()
FUNCTION (CONTINUED)
 The mysqli_info() function returns information about
queries that match one of the following formats:
 INSERT INTO...SELECT...
 INSERT INTO...VALUES (...),(...),(...)
 LOAD DATA INFILE ...
 ALTER TABLE ...
 UPDATE
For any queries that do not match one of these formats, the
mysqli_info() function returns an empty string

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 37


SUMMARY
 The mysqli_connect() function opens a connection to a
MySQL database server.
 The mysqli_close() function closes a database connection.
 The mysqli_errno() function returns the error code from the
last attempted MySQL function call or zero if no error occurred
 The mysqli_error() function returns the error message from
the last attempted MySQL function call or an empty string if no error
occurred.
 The error control operator (@) suppresses error messages
 You use the mysqli_create_db() function to create a new
database

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 38


SUMMARY (CONTINUED)
 The mysqli_select_db() function selects a database.
 You use the mysqli_drop_db() function to delete a database.
 The mysqli_query() function sends SQL statements to MySQL.
 A result pointer is a special type of variable that refers to the
currently selected row in a resultset.
 You use the CREATE TABLE statement with the
mysqli_query() function to create a table.

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 39


SUMMARY (CONTINUED)
 The PRIMARY KEY clause indicates a field or fields that will be
used as a referential index for the table
 The AUTO_INCREMENT clause creates a field that is
automatically updated with the next sequential value for that
column
 The NOT NULL clause creates a field that must contain data
 You use the DROP TABLE statement with the
mysqli_query() function to delete a table

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 40


SUMMARY (CONTINUED)
 You use the LOAD DATA statement and the
mysqli_query() function with a local text file to add
multiple records to a database
 You use the UPDATE statement with the mysqli_query()
function to update records in a table
 You use the DELETE statement with the mysqli_query()
function to delete records from a table

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 41


SUMMARY (CONTINUED)
 The mysqli_info() function returns the number of
operations for various types of actions, depending on the type
of query.
 The mysqli_fetch_row() function returns the fields in the
current row of a resultset into an indexed array and moves the
result pointer to the next row.
 The mysqli_fetch_assoc() function returns the fields in
the current row of a resultset into an associative array and
moves the result pointer to the next row
 The mysqli_free_result() function closes a resultset

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 42


SUMMARY (CONTINUED)
 The mysqli_num_rows() function returns the number of rows
in a query result, and the mysqli_num_fields() function
returns the number of fields in a query result
 With queries that return results, such as SELECT queries, you can
use the mysqli_num_rows() function to find the number of
records returned from the query

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 43


OBJECT ORIENTED WAY
To connect Database
$mysqli = new mysqli("hostname", "username", "password",
"database");
Example:
<?php
$mysqli = new mysqli("localhost", "root", "", "demo");
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
echo "Connect Successfully. Host info: " . $mysqli->host_info;

?>
PHP PROGRAMMING WITH MYSQL, 2ND EDITION 44
 Close connection <?php
$mysqli = new mysqli("localhost", "root", "", "demo");
$mysqli->close(); if($mysqli === false){
die("ERROR:. " . $mysqli->connect_error);
}
To Exucute Query
$sql = "INSERT Query”
$mysqli->query($sql) if($mysqli->query($sql) === true){
echo "Records inserted successfully.";
} else{
echo "ERROR: " . $mysqli->error;
$mysqli->close();
?>

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 45


To get number of rows from result set.
$result->num_rows // result is a query result object.
To get number one rows at a time from result..
$result->fetch_array()
To free result object.
$result->free();

PHP PROGRAMMING WITH MYSQL, 2ND EDITION 46

You might also like