Home >Documents >PHP+MySQL Integration

PHP+MySQL Integration

Date post:25-Jan-2016
View:64 times
Download:6 times
Share this document with a friend
PHP+MySQL Integration. Connecting to databases. One of the most common tasks when working with dynamic webpages is connecting to a database which holds the content of the page PHP has several libraries that allows for communication with many different databases - PowerPoint PPT Presentation
  • PHP+MySQL Integration

  • Connecting to databasesOne of the most common tasks when working with dynamic webpages is connecting to a database which holds the content of the pagePHP has several libraries that allows for communication with many different databasesSome of these libraries have variations in the commandsWe will be using the mysql libraryMost functions start with mysql_ and then the name of the function*

  • Opening a connectionYou will need:The address to the database serverA username with privileges to access the table you requireThe username associated passwordOptionally:The name of the database you are connecting*

  • Connection Sequencemysql_connect(host, username, password): returns a link to the host using username and password authentication.Usage:$conn=mysql_connect(localhost, myusername,MyP455w0rd)

    mysql_select_db(database,link): selects a database from the connection in linkUsage:mysql_select_db(db_name,$conn);*

  • Executing Queriesmysqli_query(link, query) is used to run a query on the database server. Required the link and the query string. Returns a result object.Usage:$result= mysql_query(SELECT * from directory, $conn);

    Queries can be constructed as strings and then the string variable can be used on the mysql_query command:$query="select * from directory";$result = mysql_query($query,$link) or die("could not execute:".mysql_error());*

  • Working with the results from the queryResult sets are objects. They point to places in memory where the query returned values existResult set are NOT the individual rows from the queryYou can think of a result set as the TABLE that holds the resultsYou need to read the rows from that table individually$row=mysql_fetch_array($result);Using this function, the array returned can be either numerically indexed or associative!If there are no more rows, the function returns FALSE*

  • Keeping it tidyOnce you have completed your work with the database, there are two things you should do:Free the resultsClose the connection to the server.Freeing the results can be optional: On closing the connection, the results are automatically freedIf you are planning to run further queries on the same connection, it is good practice to free the previous result set.mysql_free_result($result);To close the connection you usemysqli_close($conn);


  • Working with databases key stepsDesign the DB Create the DB on PHPMyAdmin or MySQL commandDesign and Create the HTMLCreate a connectionSelect the tableRun the queryVerify Insert/Fetch the rows/Do other SQL associated tasksDisplay Results as neededClose the connection*

  • Database Design and CreationCreate database hospital, add a table discharge with appropriate fields patient id, name, appointment type, admission ward, xray examination, mri scan, cat scan, eye test, hearing test, and date (to capture todays date)


  • Data details

    FieldTypeCommentpatidint(11) NN AI PKPrimary Key Indexnamevarchar(45)Patient Full Nameappointmentvarchar(11)type of appointment:GP, Specialist or Surgerywardchar(2)Admitted to ward? No, or ward A,B or Cxraychar(3)x-rays taken? YES,NOmrichar(3)mri carried out? YES,NOcscanchar(3)CAT scan carried out? YES,NOeyechar(3)eye test carried out? YES,NOhearingchar(3)hearing test carried out? YES,NOdatedatedate of discharge: format YYYY-MM-DD as text

  • Go ahead and create the database and table using PHPMyAdmin or MySQL command Prompt

  • Data capture form

    Patient Name:

    Appointment type

    General PracticionerSpecialistSurgery

    link to php script fileuse get to check form is working correctpost could also be used, user choicetable name3 options for app type

  • Radio buttonAdmission to Wards: No Ward Ward A Ward B Ward C

    4 options via radiobuttons, only one canbe selected on form

  • CheckboxesTreatments Undertaken:X-Ray TreatmentMRI ScanCAT ScanEye TestHearing Test

    5 options, any can be selected on form

  • Submit/reset button

  • PHP-process.php
  • Checkbox data selectionif (isset($_GET['xray'])) {$xray = $_GET['xray'];} else {$xray = "No";}Note: This code needs to be repeated for every checkbox variable passed as a parameterthe variables used are:$mri, $cscan, $eye, $hearingcheckboxes allow multiple options

    if not checked, it will not pass the parameter (not set)

    if passed the default is set to yes

    so if not passed, we need to assigna value to the respective variable that will go into the database

  • print "Name:".$name."";print "Appointment:".$app."";print "Ward:".$ward."";print "X-Ray:".$xray."";print "MRI:".$mri."";print "CSCAN:".$cscan."";print "EYE:".$eye."";print "HEARING:".$hearing."";print used to check fields are beingpassed and captured in the page

  • Database connection$link = mysql_connect('localhost','student','student') or die(mysql_error());mysql_select_db('hospital',$link);

  • Current date selection$querydate = "SELECT CURDATE() as Today";$result1 = mysql_query($querydate,$link) or die(mysql_error());$row = mysql_fetch_assoc($result1);$today = $row['Today'];This script demonstrates how the current datecan be obtained from the MySQL server using the appropriate DATE queryThe parameter being queried (date)does not have an index in the array,so we need to use the alias AS to assignan index that we can use to retrieve fromthe result array

  • INSERT data$query = "INSERT INTO discharge VALUES (NULL,'$name','$app','$ward','$xray','$mri','$cscan','$eye','$hearing','$today')";$result = mysql_query($query,$link) or die(mysql_error());$affected = mysql_affected_rows($link);

    if ($affected >0) {echo "success";} else {echo "fail";}detects affected rows in the queryin this case 1 row was INSERTED so$affected=1 if the insert was successfulgenerates my-sql error causesQuery to insert all data from html form + date obtained from previous query

  • Selection to display all$query3 = "SELECT * FROM discharge";$result3 = mysql_query($query3,$link) or die(mysql_error());$row3 = mysql_fetch_assoc($result3);?>This is another query to retrieve all the datafrom the table discharge

  • Table design for results

    Patient ID Patient Name Appointment Type Admitted to Ward X-Ray MRI Cat Scan Eye Test Hearing Test Date Discharged

  • Results

    $row is an associative array containing the results,the index of the array are the fields in the database

  • do . while loop

    DO-WHILE Loopneeded to display all the results of the database

  • Close connection

  • Places where things can go wrongCreating a connectionServer unreachable/offlineWrong username/password combinationSelecting the tableTable does not existUser without privileges for that tableRunning the querySyntax errorsEmpty result setFetching resultsMisusing the array


Click here to load reader

Embed Size (px)