1. 程式人生 > >php +ajax +sql 實現資料互動

php +ajax +sql 實現資料互動

1.首先新建個sql表,表內容如上所示:

2.新建個公用檔案conn.php來連結資料庫:

<?phpheader("Content-Type:text/html;charset=utf8");//申明編碼格式
$conn=mysql_connect("localhost","root","aaaaaa") or die("資料庫連線錯誤".mysql_errno());//連線sql
mysql_select_db("phptest",$conn);
mysql_query('SET NAMES UTF8') or die('字符集設定錯誤'.mysql_error());//設定輸入的字符集編碼
?>
3.php服務端提供給前端ajax資料介面,新建檔案phptoAJAX。php
<?phprequire_once("conn.php");//匯入公用檔案$query=mysql_query("SElECT * FROM txt") or die("錯誤提示:".mysql_error());
$jsonArray=array();//新建資料用於接收資料庫每行對應的資料組while($rows=mysql_fetch_array($query))
{
//處理資料庫裡面的自動對應的內容$rows['content']=mb_substr(strip_tags(htmlspecialchars_decode
($rows['content'])),0,100,"utf-8"); //把資料庫的內容新增到新建陣列中
   array_push($jsonArray,$rows);//注意這裡是$rows}
echo json_encode($jsonArray);//轉換成json傳遞給前端
4.新建phpToAJAX.HTML前端接收資料,這裡我用jquery封裝好的ajax方法,執行後的頁面如下圖所示:
<!DOCTYPE html><html><head lang="en"><meta charset="UTF-8"><title></title>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script></head><body><ul id="list">
 <!--資料將在這裡顯示-->
</ul>
<script type="text/javascript">
$(function(){  
$.ajax({    
type: "post",//傳遞方法
url: "phpToAJAX.php",//資料介面
dataType: "json",//接收格式
success: function(msg)//如果接收成功執行以下
           {   
var li="";    
            for(var i =0;i<msg.length-1;i++)//這裡是限定10
{   
                li+="<li><h2>"+msg[i]['title']+"</h2><p>"+msg[i]['content']+"...<a href='phpArtcle.php?art="+msg[i]['id']+"' target='_blank'>詳細</a></p></li>";                   }   
             $("#list").html(li);
      },   
error:function()//如果接收不成功執行以下
            {    
                console.log("連結錯誤")
            }
        });
    });

</script></body></html>
5.點選上一步圖中所示的“詳細”連結,可檢視對應的文章內容,新建phpArtcle.php檔案
<?phprequire_once("conn.php");
$id=$_GET['art'];//接收前端上傳的資料
//查詢資料庫對應的內容
$query=mysql_query("SELECT * FROM txt WHERE  id='$id'") or die("文章錯誤:".mysql_error());
//遍歷陣列,顯示內容
if($rows=mysql_fetch_array($query)){echo "<h1>".$rows['title']."</h1>";echo "<div>".htmlspecialchars_decode($rows['content'])."</div>";}-------------------完畢-----------------------