Post on 30-Jun-2020
1
Use of PHP for DB Connection
2
Client:UI
Middle Get all books with keyword “web programming”
DBQuery
Format the output, i.e., data returned from the DBPHP
HTML, JavaScript, CSS,XML
SQL
Access/MySQL
3 4
Middle and Information TierPHP: built in library functions for interfacing with the mySQL database management system
$id = mysqli_connect(string hostname, string username, string password, string db)
Connection to the MySQL serverReturn false if fails
$result = $id->query(string query)Execute a SQL query: return a result handle that will be used to fetch the result
5
Middle and Information TierPHP: built in function for mySQL
$result->data_seek(0);Go to the first row of the result
$row=$result->fetch_assoc()Fetch the row of the results Combine with a while loop to read all rows
$id->close()Close the connection
StepsCreate DB “pharmacy”
dbPharmacy.txtlocalhost/phpmyadmin
11 12
Define a SQL string
Execution
Data processing
DB connection
13
ExerciseModify previous examples to show the following info:
14
Database Modification: InsertSyntax:
INSERT INTO table_name VALUES (value1, value2, ….)
Step:DB connectionDefine a string containing the SQL commandExecute the sql statement
15
Database Modification: ModifySyntax:
UPDATE table_name SET column_name_i = new_value where column_name_j=some_value
Step:DB connectionDefine a string containing the SQL commandExecute the sql statement
16
AJAX and DB
17
AJAX and DatabaseDisplay info in one page
Display info whenever the info is received
18
A Possible ApproachUsing get method
If there is a salesperson’s name in the URL, then display the required informationOtherwise, display the form only
Require HTML or PHP file?Two parts:
a form to be displayedA db query to display the required info
20
<form method="GET" action=“query2.php"><p> Select a salesperson to display the info:
<select name="select"><option value="Abel" selected="selected"> Abel </option><option value="Baker"> Baker </option><option value="Jones"> Jones </option><option value="Kobad"> Kobad </option><option value="Murphy"> Murphy </option><option value="Zenith"> Zenith </option>
</select> </p><p> <input type="submit" value="Query" /> </p>
</form>
21
<?phpif (isset($_GET["select"]) and $_GET["select"] !=NULL) {
$q = $_GET["select"]; $conn = mysqli_connect("localhost", "root", "","pharmacy");if ($conn->connect_error) {
echo "Unable to connect to database"; exit; }print("<h1> Sales person: " . $q . "</h1>");$query1 = "select salary from salesperson where
SalesName= '" . $q . "'";$result1 = $conn->query($query1);if (!$result1) die("No information");$result1->data_seek(0);while ($row=$result1->fetch_assoc()) {
print("<h2> Salary: " . $row["salary"] . "</h2>");} …
22
SynchronousAsynchronousAsynchronous requests
Browser Server
Request the php file
Display the form only
A get request
Display the form + order info
23
AJAX Approach2 files
Html fileA formA JavaScript function
Make asynchronous connectionCall to the php file, display the information when it is ready
Php fileQuery the db to get the desired info
24
<script type="text/javascript">var xmlHttp;function showInfo(str) {
try{ xmlHttp = new XMLHttpRequest();} catch (e){
try{xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");} catch (e){
alert(“Error!"); return ;}
}}
25
var url = "phpSales.php?q=" + str;
xmlHttp.onreadystatechange=function() {if (xmlHttp.readyState == 4) {
disInfo.innerHTML = xmlHttp.responseText;}
}xmlHttp.open("GET", url, true);xmlHttp.send(null);
}</script>
26
<form><p> Select a salesperson to display the info:
<select name="select" onchange="showInfo(this.value)"><option value="Abel" selected="selected"> Abel </option><option value="Baker"> Baker </option><option value="Jones"> Jones </option><option value="Kobad"> Kobad </option><option value="Murphy"> Murphy </option><option value="Zenith"> Zenith </option>
</select> </p></form><div id="disInfo"> </div>
27
display.php$q = $_GET["select"]; $conn = mysqli_connect("localhost", "root", "","pharmacy");if ($conn->connect_error) {
echo "Unable to connect to database"; exit; }print("<h1> Sales person: " . $q . "</h1>");$query1 = "select salary from salesperson where
SalesName= '" . $q . "'";$result1 = $conn->query($query1);if (!$result1) die("No information");$result1->data_seek(0);while ($row=$result1->fetch_assoc()) {
print("<h2> Salary: " . $row["salary"] . "</h2>");} …
29
POST
var url = ”display.php";var queryvalue = encodeURIComponent(str);var parameters = "q="+queryvalue;xmlHttp.open("POST", url, true);xmlHttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");xmlHttp.send(parameters);
30
Application designDesign application in tiersEach tier can be run a separate machine, allowing for improved processing performancePromote scalabilityEase long term maintenance requirements for your code
Client tier Middle tier Information tier
31
Application designPHP:
Server side scripting languageSQL:
Language used to query the relational databaseWHERE, ORDER BY, COUNT(*)
Processing in PHP or SQL?Sorting, pattern matching in records
32
Application designSQL:
Language specifically designed to query and retrieve data from your tables!!
Filter out unnecessary data using SQL, leaving a relevant data set for PHP to work with
Selecting statement, WHERE conditionORDER BY: sorting
FASTER CODE, NETWORK LOAD
33
ComponentsSetting up a siteDesign the web documents
Client side techniques: CSS, JavaScript, DHTML
Server side techniquesScripting languages, how to access database
Administrating a web site: IMPORTANTDifficult to keep all documents/information up to date easily
34
InformationMaintenance of a content-driven site can be a real painSolution: database-driven site designComplete separation between the site design and the content you want to presentDon’t write an HTML file for every page of your siteWrite a page for each kind of information you want to present
35
IdeaDatabase:
content of the siteDynamically pulled from the database to create web pages
Template HTML page:
For each kind (type) of information
browserWeb server
PHP fileMySQ
L
36
ModelOn the visitor’s end:
Expects to view a standard HTML web page
On the other endHave a database that only understands how to respond to SQL queries
PHP scripting languagego-between that speaks both languages