📄 php_ajax_database.asp@output=print
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PHP and AJAX MySQL Database Example</title>
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta name="Keywords" content="xml,tutorial,html,dhtml,css,xsl,xhtml,javascript,asp,ado,vbscript,dom,sql,colors,soap,php,authoring,programming,training,learning,beginner's guide,primer,lessons,school,howto,reference,examples,samples,source code,tags,demos,tips,links,FAQ,tag list,forms,frames,color table,w3c,cascading style sheets,active server pages,dynamic html,internet,database,development,Web building,Webmaster,html guide" />
<meta name="Description" content="Free HTML XHTML CSS JavaScript DHTML XML DOM XSL XSLT RSS AJAX ASP ADO PHP SQL tutorials, references, examples for web building." />
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "../../https@ssl./default.htm" : "../../www./default.htm");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-3855518-1");
pageTracker._initData();
pageTracker._trackPageview();
</script>
<script src="selectuser.js" type="text/javascript"></script>
</head>
<body>
<p>From <b>http://www.w3schools.com</b> (Copyright Refsnes Data)</p>
<h1>PHP and AJAX MySQL Database Example</h1>
<a href="php_ajax_xml.asp"><img border="0" src="../images/btn_previous.gif" width="100" height="20" alt="Previous" /></a>
<a href="php_ajax_responsexml.asp"><img border="0" src="../images/btn_next.gif" width="100" height="20" alt="Next" /></a>
<hr />
<p class="intro">AJAX can be used for interactive communication with a database.</p>
<hr>
<h2>AJAX Database Example</h2>
<p>In the AJAX example below we will demonstrate how a web page can fetch
information from a MySQL database using AJAX technology.</p>
<hr>
<h2>Select a Name in the Box Below</h2>
<form>
Select a User:
<select name="users" onchange="showUser(this.value)">
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br />
<div id="txtHint"><b>User info will be listed here.</b></div><p/>
<p>This example consists of four elements:</p>
<ul>
<li>a MySQL database</li>
<li>a simple HTML form</li>
<li>a JavaScript</li>
<li>a PHP page</li>
</ul>
<hr>
<h2>The Database</h2>
<p>The database we will be using in this example looks like this:</p>
<table border="1" width="100%" id="table9">
<tr>
<th>id</th>
<th>FirstName</th>
<th>LastName</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>
<tr>
<td>1</td>
<td>Peter</td>
<td>Griffin</td>
<td>41</td>
<td>Quahog</td>
<td>Brewery</td>
</tr>
<tr>
<td>2</td>
<td>Lois</td>
<td>Griffin</td>
<td>40</td>
<td>Newport</td>
<td>Piano Teacher</td>
</tr>
<tr>
<td>3</td>
<td>Joseph</td>
<td>Swanson</td>
<td>39</td>
<td>Quahog</td>
<td>Police Officer</td>
</tr>
<tr>
<td>4</td>
<td>Glenn</td>
<td>Quagmire</td>
<td>41</td>
<td>Quahog</td>
<td>Pilot</td>
</tr>
</table>
<p/>
<hr>
<h2>The HTML Form</h2>
<p>The example above contains a simple HTML form and a link to a JavaScript:</p>
<table class="ex" id="table6" border="1" width="100%">
<tr>
<td>
<pre><html>
<head>
<script src="selectuser.js"></script>
</head>
<body></pre>
<pre><form>
Select a User:
<select name="users" onchange="showUser(this.value)">
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form></pre>
<pre><p>
<div id="txtHint"><b>User info will be listed here.</b></div>
</p></pre>
<pre></body>
</html></pre>
</td>
</tr>
</table>
<h2>Example Explained - The HTML Form</h2>
<p>As you can see it is just a simple HTML form with a drop down box called
"users" with names and the "id" from the database as option values.</p>
<p>The paragraph below the form contains a div called "txtHint". The div is used
as a placeholder for info retrieved from the web server.</p>
<p>When the user selects data, a function called "showUser()" is executed.
The execution of the function is triggered by the "onchange" event.</p>
<p>In other
words: Each time the user changes the value in the drop down box, the function
showUser() is called.</p>
<hr>
<h2>The JavaScript</h2>
<p>This is the JavaScript code stored in the file "selectuser.js":</p>
<table class="ex" id="table7" border="1" width="100%">
<tr>
<td>
<pre>var xmlHttp</pre>
<pre>function showUser(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="getuser.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}</pre>
<pre>function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}</pre>
<pre>function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}</pre>
</td>
</tr>
</table>
<h2>Example Explained</h2>
<p>The stateChanged() and GetXmlHttpObject functions are the same as in the
<a href="php_ajax_suggest.asp">PHP AJAX Suggest</a> chapter, you can go
to there for an explanation of those.</p>
<p><b>The showUser() Function</b></p>
<p>If an item in the drop down box is selected the function
executes the following:</p>
<ol>
<li>Calls on the GetXmlHttpObject function to create an XMLHTTP object</li>
<li>Defines the url (filename) to send to the server</li>
<li>Adds a parameter (q) to the url with the content of the dropdown box
</li>
<li>Adds a random number to prevent the server from using a cached file</li>
<li>Call stateChanged when a change is triggered</li>
<li>Opens the XMLHTTP object with the given url.</li>
<li>Sends an HTTP request to the server</li>
</ol><hr>
<h2>The PHP Page</h2>
<p>The server page called by the JavaScript, is a simple PHP file called
"getuser.php".</p>
<p>The page is written in PHP and uses a MySQL databse.</p>
<p>The code runs a SQL query against a database and returns the result as an HTML
table:</p>
<table class="ex" id="table8" border="1" width="100%">
<tr>
<td>
<pre><?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</pre>
</td>
</tr>
</table>
<h2>Example Explained</h2>
<p>When the query is sent from the JavaScript to the PHP page the following
happens:</p>
<ol>
<li>PHP opens a connection to a MySQL server</li>
<li>The "user" with the specified name is found</li>
<li>A table is created and the data is inserted and sent to the "txtHint"
placeholder</li>
</ol>
<hr />
<a href="php_ajax_xml.asp"><img border="0" src="../images/btn_previous.gif" width="100" height="20" alt="Previous" /></a>
<a href="php_ajax_responsexml.asp"><img border="0" src="../images/btn_next.gif" width="100" height="20" alt="Next" /></a>
<p>From <b>http://www.w3schools.com</b> (Copyright Refsnes Data)</p>
</body>
</html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -