簡體   English   中英

通過Ajax使用PHP在MySQL中插入和檢索數據

[英]Inserting and retrieving data in MySQL using PHP through Ajax

我有一個非常簡單的表單,其中包含一個文本框和一個提交按鈕。 當用戶在表單中輸入內容,然后單擊提交時,我想使用PHP和Ajax(使用jQuery)將表單的結果插入MySQL數據庫。 此結果應以表格的形式顯示在同一頁上,該表格在每次插入后都會更新。

誰能幫忙嗎?

我使用的代碼無法正常工作:

ajax.html

<html>
<body>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
 var ajaxRequest;  // The variable that makes Ajax possible!

 try{
   // Opera 8.0+, Firefox, Safari
   ajaxRequest = new XMLHttpRequest();
 }catch (e){
   // Internet Explorer Browsers
   try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
      try{
         ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e){
         // Something went wrong
         alert("Your browser broke!");
         return false;
      }
   }
 }
 // Create a function that will receive data 
 // sent from the server and will update
 // div section in the same page.
 ajaxRequest.onreadystatechange = function(){
   if(ajaxRequest.readyState == 4){
      var ajaxDisplay = document.getElementById('ajaxDiv');
      ajaxDisplay.value = ajaxRequest.responseText;
   }
 }
 // Now get the value from user and pass it to
 // server script.
 var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
 var wpm = document.getElementById('wpm').value;
 var sex = document.getElementById('sex').value;
 var queryString = "&name=" +name+ "&age=" + age ;
 queryString +=  "&wpm=" + wpm + "&sex=" + sex;
 ajaxRequest.open("GET", "ajax-example.php" + 
                              queryString, true);
 ajaxRequest.send(null); 
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' id='name' /><br/>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()' 
                              value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>

ajax-example.php

<?php
$dbhost = "localhost";
$dbuser = "demo";
$dbpass = "demo";
$dbname = "test_db";
    //Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
    //Select Database
mysql_select_db($test_db) or die(mysql_error());
    // Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
    // Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
    //build query
$query = "INSERT INTO form2 (name,age,sex,wpm) VALUES ('$name','$age','$sex','$wpm')";;


mysql_select_db('test_db');

$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not enter data: ' . mysql_error());
}

    //Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";

// Insert a new row in the table for each person returned
$result1=mysql_query("SELECT * FROM form2 WHERE name='$name'"); 
while($row = mysql_fetch_array($result1))
{
    $display_string .= "<tr>";
    $display_string .= "<td>$row[name]</td>";
    $display_string .= "<td>$row[age]</td>";
    $display_string .= "<td>$row[sex]</td>";
    $display_string .= "<td>$row[wpm]</td>";
    $display_string .= "</tr>";

}

$display_string .= "</table>";
echo $display_string;
?>
$("button_id").click(function () {
    $.ajax({
        url:"where you should post the data",
        type: "POST",  
        data: the string you should post,  
        success: function (result) {
            //display your result in some DOM element
        }
    });
});

當您在php腳本中收到數據時,請查詢數據庫並獲取結果

希望這會有所幫助

互聯網上有許多可用於PHP和Jquery的Ajax教程。 您可以完成所有這些操作,然后獲得想要的結果。

在此處查看示例http://www.tutorialspoint.com/ajax/ajax_database.htm

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM