Home >Documents >Lec_6 Manipulating MySQL Databases with PHP PHP Programming with MySQL

Lec_6 Manipulating MySQL Databases with PHP PHP Programming with MySQL

Date post:01-Jan-2016
Category:
View:232 times
Download:3 times
Share this document with a friend
Transcript:
  • Lec_6

    Manipulating MySQLDatabases with PHP

    PHP Programming with MySQL

    Name of Book

  • Opening a MySQL ConnectionOpen a connection to a MySQL database with mysqli_connect()Returns a positive integer if connection is successful Returns false if it is not Assign the return value to a variable$connection = mysqli_connect("host"[, "user ", "password", "database"])host specifies where MySQL database server residesuser and password specify MySQL username and passworddatabase selects a database with which to work

    Name of Book

  • Selecting a DatabaseSelect a database when connecting ORUse mysqli_select_db() functionSyntaxmysqli_select_db(connection, database)Use connection variable returned by mysqli_connect()Return valueTrue if database is selected successfullyFalse if it is notAlso enables you to change current database

    Name of Book

  • Closing a Database ConnectionAny open database connections are closed automatically when a PHP script ends.Should be closed explicitly when you are finished with the connectionReleases memorymysqli_close($connection)

    Name of Book

  • Example$connect = mysqli_connect(localhost, tostrand, tjo123);mysqli_select_db($connect, e-commerce);mysqli_close($connect);

    Name of Book

  • Handling MySQL ErrorsReasons for failure to connect to a database server include:The database server is not runningInsufficient privileges to access the data sourceInvalid username and/or password

    Name of Book

  • Suppressing Errors with the Error Control OperatorWriting code that anticipates and handles potential problems is called bulletproofingBulletproofing techniques include:Validating submitted form dataUsing the error control operator (@) to suppress error messagesProviding your own custom (user-friendly) error messages

    Name of Book

  • Terminating Script ExecutionThe die() function terminates script executionAccepts a single string argumentCall the die() as a separate statement ORAppend the function call to an expression with the Or operator

    Name of Book

  • Terminating Script Execution

    $DBConnect = @mysqli_connect("localhost", "root", "paris");if (!$DBConnect)die("The db server is not available.");echo "Successfully connected to the db server.";$DBSelect = @mysqli_select_db($DBConnect, "flightlog");if (!$DBSelect)die("The database is not available.");echo "Successfully opened the database.";// additional statements that access the databasemysqli_close($DBConnect);

    Name of Book

  • Terminating Script Execution

    $DBConnect = @mysqli_connect("localhost", "dongosselin", "rosebud")Or die("The db server is not available.");echo "Successfully connected to the db server.";@mysqli_select_db($DBConnect, "flightlog")Or die("The database is not available.");echo "Successfully opened the database.";// additional statements that access the database servermysqli_close($DBConnect);

    Name of Book

  • MySQL Error Reporting Functions

    Name of Book

  • Reporting MySQL Errors

    $User = $_GET['username'];$Password = $_GET['password'];$DBConnect = @mysqli_connect("localhost", $User, $Password)Or die("Unable to connect to the database server.". "Error code " . mysqli_connect_errno(). ": " . mysqli_connect_error()) . ""; echo "Successfully connected to the database server.";@mysqli_select_db($DBConnect, "flightlog")Or die("Unable to select the database.". "Error code " . mysqli_errno($DBConnect). ": " . mysqli_error($DBConnect)) . ""; echo "Successfully opened the database.";// additional statementsmysqli_close($DBConnect);

    Name of Book

  • Executing SQL Statementsmysqli_query() function sends SQL statements to MySQL databasemysqli_query(connection, query)Returns one of three values:For SQL statements that do not return results (e.g. CREATE TABLE, INSERT), returns true if the statement executes successfullyFor SQL statements that return results (e.g. SELECT), returns a result pointer that represents the query resultsRefers to the currently selected row in a resultsetReturns false for any SQL statements that fail, regardless of whether they return results

    Name of Book

  • Working with Query Resultsmysqli_fetch_row() returns fields in the current row into an indexed arraymysqli_fetch_assoc() returns fields in the current row into an associative arraymysqli_fetch_array() returns fields in the current row into an indexed array or associative array

    Name of Book

  • mysqli_fetch_row()Returns the fields in the current row of a resultset into an indexed array Moves the result pointer to the next row

    echo "

  • Name of Book

  • mysqli_fetch_assoc()The function returns the fields in the current row of a resultset into an associative array Moves the result pointer to the next rowEach field name is used as an array keyecho "
  • Accessing Query Result Informationmysqli_num_rows() returns the number of rows in a query resultmysqli_num_fields() returns the number of fields in a query resultBoth functions accept a database connection variable as an argument

    Name of Book

  • $SQLstring = "SELECT * FROM inventory";$QueryResult = @mysqli_query($DBConnect, $SQLstring)Or die("Unable to execute the query.". "Error code . mysqli_errno($DBConnect). ": " . mysqli_error($DBConnect)) . "";echo "Successfully executed the query.";$NumRows = mysqli_num_rows($QueryResult);$NumFields = mysqli_num_fields($QueryResult);if ($NumRows != 0 && $NumFields != 0)echo "Your query returned " . mysqli_num_rows($QueryResult) . " rows and ". mysqli_num_fields($QueryResult) . " fields.";elseecho "Your query returned no results.";mysqli_close($DBConnect);

    Name of Book

  • Name of Book

  • Closing Query ResultsWhen you are finished working with query results, use the mysqli_free_result() function to close the resultset.Takes query result as a parametermysqli_free_result($queryResult);Only works when the SQL statement returns results.

    Name of Book

  • Creating DatabasesUse the CREATE DATABASE statement with the mysqli_query() function to create a new databaseUse mysqli_db_select() to check whether a database exists before you create or delete itTo use a new database, select it by executing the mysqli_select_db() functionUse the DROP DATABASE statement with the mysqli_query() function to delete a database

    Name of Book

  • $DBName = "real_estate";...if (@mysqli_select_db($DBConnect, $DBName))echo "The $DBName database already exists!";else {$SQLstring = CREATE DATABASE $DBName";$QueryResult = @mysqli_query($DBConnect, $SQLstring)Or die("Unable to execute the query.". "Error code . mysqli_errno($DBConnect). ": . mysqli_error($DBConnect)) . "";echo "Successfully created the database.";mysqli_select_db($DBConnect, $DBName);}

    Name of Book

  • Creating TablesTo create a table, use the CREATE TABLE statement with the mysqli_query() functionExecute the mysqli_select_db() function before executing the CREATE TABLE statement Prevents the new table from being created in the wrong databaseUse mysqli_query() to ensure that the table doesnt already exist

    Name of Book

  • $DBName = "real_estate";...$SQLstring = "CREATE TABLE commercial (city VARCHAR(25), state VARCHAR(25), sale_or_lease VARCHAR(25), type_of_use VARCHAR(40), price INT, size INT)";$QueryResult = @mysqli_query($DBConnect, $SQLstring)Or die("Unable to execute the query.". "Error code " . mysqli_errno($DBConnect). ": " . mysqli_error($DBConnect)) . "";echo "Successfully created the table.";mysqli_close($DBConnect);

    Name of Book

  • Adding RecordsTo add records to a table, use an INSERT statement with the mysqli_query() functionINSERT INTO tableName VALUES (val1, val2, val3)The values entered in the VALUES list must be in the same order as the table fieldsSpecify NULL in any fields for which you do not have a valueField definition must allow NULL values or an error will occur

    Name of Book

  • Updating RecordsTo update records in a table, use an UPDATE statement with the mysqli_query() functionThe WHERE keyword determines which records to update in the table

    UPDATE tableName SET field = value WHERE condition;UPDATE books SET title = PHP Made Simple WHERE isbn = 123-45-6889;

    Name of Book

  • Deleting RecordsTo delete records in a table, use a DELETE statement with the mysqli_query() functionThe WHERE keyword determines which records to delete in the table

    DELETE FROM tableName WHERE condition;DELETE FROM books WHERE isbn = 123-45-6889;

    Name of Book

  • More Functionsmysqli_num_rows() Find the number of records returned from a SELECT querymysqli_affected_rows() Determine the number of rows affected by an INSERT, UPDATE or DELETE query

    Name of Book

  • $SQLstring = "UPDATE inventory SET price=368.20WHERE make='Fender' AND model='DG7'";$QueryResult = @mysqli_query($DBConnect, $SQLstring)Or die("Unable to execute the query.". "Error code " . mysqli_errno($DBConnect). ": " . mysqli_error($DBConnect)) . "";echo "Successfully updated " . mysqli_affected_rows($DBConnect) . " record(s).";

    Name of Book

Click here to load reader

Reader Image
Embed Size (px)
Recommended