Ajax PHP learn and practice three databases

  • 2020-03-31 17:13:31
  • OfStack

This article continues with an example of how to interact with a database. The example is MySQL, you can also replace it with other databases according to your own needs, and you can refer to the relevant PHP manuals for the connection method.

In the lower source package, dbconnector.php provides a connection function to MySQL.
 
<?php 
//Define data connection variables
define ("MYSQLHOST", "localhost"); 
define ("MYSQLUSER", "root"); 
define ("MYSQLPASS", "root"); 
define ("MYSQLDB", "test"); 

function opendatabase(){ 
//Connect to the server where the database resides
$db = mysql_connect (MYSQLHOST,MYSQLUSER,MYSQLPASS); 
try { 
if (!$db){ 
//An error occurs if you cannot connect
$exceptionstring = "Error connection to database: <br />"; 
$exceptionstring .= mysql_errno().": ".mysql_error(); 
throw new exception ($exceptionstring); 
} 
else{ 
//Connect to database (test)
mysql_select_db (MYSQLDB,$db); 
} 
return $db; 
}catch (exception $e){ 
echo $e->getmessage(); 
die(); 
} 
} 
?> 

The checkfortasks function in functions.js is called when the mouse is over a date. At the same time, checkfortasks loads the taskchecker.php program, which queries MySQL for all memos under that date and returns the results to the page.
 
<?php 
//Invoke the database connector
require_once ("dbconnector.php"); 
//Connect to database
$db = opendatabase(); 
//Query memos in MySQL
$querystr = "SELECT description FROM task WHERE thedate='" . addslashes ($_GET['thedate']) . "'"; 
//Execute SQL
if ($datequery = mysql_query ($querystr)){ 
//Determines whether the query has a value
if (mysql_num_rows ($datequery) > 0){ 
?> 
<div style="width: 150px; background: #FFBC37; border-style: solid; border-color: #000000; border-width: 1px;"> 
<div style="padding: 10px;"> 
<?php 
//Display memo information
while ($datedata = mysql_fetch_array ($datequery)){ 
if (!get_magic_quotes_gpc()){ 
echo stripslashes ($datedata['description']); 
} 
else{ 
echo $datedata['description']; 
} 
} 
?> 
</div> 
</div> 
<?php 
} 
} 
else{ 
//Database query error
echo mysql_error(); 
} 
//Close the database
mysql_close ($db); 
?> 

The principles for using Ajax are the same as in the previous article: 1. 2. Request other PHP programs through functions, which can read, write and modify data sources such as database; 3. Load the processing results into the event trigger page. When you mouse over the 26th in the figure below, Ajax queries the "Football Match" event in MySQL and loads it into the current page.
(link: https://www.jb51.net/upload/2009-11/20091126012904155.png)  
(link: http://xiazai.jb51.net/200911/yuanma/ajax_php_database.rar)

Related articles: