07_PHP_Lecture
07_PHP_Lecture
2
Connecting to MySQL with PHP
• PHP has the ability to access and manipulate
any database that is ODBC compliant
$DBConnect = mysql_connect("localhost",
“root", “myPassword");
mysql_close($DBConnect);
7
Opening and Closing a MySQL
Connection (continued)
8
Opening and Closing a MySQL
Connection (continued)
9
Reporting MySQL Errors
10
Reporting MySQL Errors
(continued)
• The mysql_errno() function returns the error
code from the last attempted MySQL function call
or 0 if no error occurred
13
Sample Code
$host = 'localhost';
$userName = 'root';
$password = '*****';
$database = 'myDatabase';
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_close($link);
14
Sample Code
<?php
$link = mysql_connect('localhost', root', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db(my_database', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>
15
Suppressing Errors with the Error
Control Operator
• By default, functions in the mysql package
display errors and warnings as they occur
// Formulate Query
// For more examples, see mysql_real_escape_string()
$query = "SELECT firstname, lastname, address, age FROM friends WHERE firstname=‘$firstname ‘ AND lastname= ‘$lastname’”;
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
$con = mysql_connect("localhost",“root",“my_password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");
mysql_close($con);
?>
21
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 clause
• To delete records in a table, use the DELETE
statement with the mysql_query() function
• Omit the WHERE clause to delete all records in
a table
22
Adding, Deleting, and Updating
Records
<?php
$con = mysql_connect("localhost",“root",“my_password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET Age = '36'
WHERE FirstName = 'Peter' AND LastName = 'Griffin'");
mysql_close($con);
?>
23
Retrieving Records into an
Indexed Array
• The mysql_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 = mysql_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 = mysql_fetch_row($QueryResult);
} while ($Row); 24
Sample Code
<?php ng";
exit;
$conn = mysql_connect("localhost", "mysql_user", }
"mysql_password");
// While a row of data exists, put that row in $row a
if (!$conn) { s an associative array
echo "Unable to connect to DB: " . mysql_error(); // Note: If you're expecting just one row, no need to
exit; use a loop
} // Note: If you put extract($row); inside the following
loop, you'll
if (!mysql_select_db("mydbname")) { // then create $userid, $fullname, and $userstat
echo "Unable to select mydbname: " . mysql_err us
or(); while ($row = mysql_fetch_assoc($result)) {
exit; echo $row["userid"];
} echo $row["fullname"];
echo $row["userstatus"];
$sql = "SELECT id as userid, fullname, userstatus }
FROM sometable
WHERE userstatus = 1"; mysql_free_result($result);
$result = mysql_query($sql); ?>
if (!$result) {
echo "Could not successfully run query ($sql) fro
m DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiti 25
Using the mysql_affected_rows()
Function
• With queries that return results (SELECT queries),
use the mysql_num_rows() function to find the
number of records returned from the query
27
Using the mysql_affected_rows()
Function (continued)
28
Using the mysql_info() Function
• For queries that add or update records, or alter
a table’s structure, use the mysql_info()
function to return information about the query
• The mysql_info() function returns the
number of operations for various types of
actions, depending on the type of query
• The mysql_info() function returns information
about the last query that was executed on the
database connection
29
Using the mysql_info() Function
(continued)
• The mysql_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 mysql_info() function returns an
empty string
30
Using the mysql_info() Function
(continued)
$SQLstring = "INSERT INTO company_cars " .
" (license, model_year, make, model, mileage) " .
" VALUES " .
" ('CPQ-894', 2011, 'Honda', 'Insight', 49.2), " .
" ('CPQ-895', 2011, 'Honda', 'Insight', 17.9), " .
" ('CPQ-896', 2011, 'Honda', 'Insight', 22.6)";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else {
echo "<p>Successfully added the record.</p>";
echo "<p>" . mysql_info($DBConnect) . "</p>";
}
31
Using the mysql_info() Function
(continued)
32
Using the mysql_info() Function
(continued)
• The mysql_info() function also returns
information for LOAD DATA queries
$SQLstring = "LOAD DATA INFILE 'company_cars.txt'
INTO TABLE company_cars;";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else {
echo "<p>Successfully added the record.</p>";
echo "<p>" . mysql_info($DBConnect) . "</p>";
}
33
Using the mysql_info() Function
(continued)
34
Working with Query Results
35
Retrieving Records into an Indexed
Array
• The mysql_fetch_row() function returns the
fields in the current row of a result set into an
indexed array and moves the result pointer to
the next row
36
Retrieving Records into an Indexed
Array
$SQLstring = "SELECT * FROM company_cars";
$QueryResult = @mysql_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 = mysql_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";
37
Retrieving Records into an Indexed
Array
38
Retrieving Records into an
Associative Array
• The mysql_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
41
Accessing Query Result Information (continued)
42
Accessing Query Result
Information (continued)
43
Summary
50
Summary (continued)
52
Creating and Deleting Tables
(continued)
$SQLstring = "CREATE TABLE drivers (name VARCHAR(100), "
. "emp_no SMALLINT, hire_date DATE, "
. "stop_date DATE)";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult===FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " .
mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) .
"</p>";
else
echo "<p>Successfully created the table.</p>";
53
Creating and Deleting Tables
(continued)
54
Creating and Deleting Tables
(continued)
• Use the SHOW TABLES LIKE command to
prevent code from trying to create a table that
already exists.
• If the table does not exist, the
mysql_num_rows()function will return a value
of 0 rows
$TableName = "subscribers";
$SQLstring = "SHOW TABLES LIKE '$TableName'";
$QueryResult = @mysql_query($SQLstring,
$DBConnect);
55
Creating and Deleting Tables
(continued)
• To identify a field as a primary key in MySQL,
include the PRIMARY KEY keywords when you
define a field with the CREATE TABLE
statement
• The AUTO_INCREMENT keyword is often used
with a primary key to generate a unique ID for
each new row in a table
• The NOT NULL keywords are often used with
primary keys to require that a field include a
value
56
Creating and Deleting Tables
(continued)
57
Creating a Database
• Use the mysql_create_db() function to create a
new database
59
Deleting a Database
• To delete a database, use the
mysql_drop_db() function.
• The format for the mysql_drop_db() function
is:
$Result = mysql_drop_db("dbname" [,
connection]);
• The function returns a value of TRUE if it
successfully drops a database or FALSE if it
does not
60