1. 程式人生 > >MySQL資料庫:主要學習瞭如何用php操作資料庫

MySQL資料庫:主要學習瞭如何用php操作資料庫

1.MySQL資料庫簡介

按照一個圖表去理解

2.MySQL資料庫的視覺化工具

(1)phpmyadmin
(2)Navicat for MySQL

3.視覺化工具的【增刪改查】操作

兩種方法

4.php連線資料庫與基本操作配置

(1)php建立資料庫【連線】
語法:Object mysqli_connect("域名","DB賬號","DB密碼","DB庫名")
例子:$con = mysqli_connect('localhost','root','','frankdb');
(2)向DB中插入資料時包含中文出現亂碼的解決方案
語法:mysqli_query($con,"set names utf8");


說明:設定成功會返回1,根據實際情況並不一定必須儲存返回結果。
(3)設定client端和server端保持字元編碼一致
語法:mysqli_query($con,"set character_set_client=utf8");

mysqli_query($con,"set character_set_results=utf8");

(4)執行sql語句
語法:$結果 = $DB連線->query(sql語句);
例子:var_dump($result = $con->query($sql));

5.php操作資料庫【增刪改查】操作

(1)使用sql語句基本【模板】

$con = mysqli_connect('localhost','root','','frankdb');      //建立連線
if($con){                                        //判斷是否連線
	echo "<pre>";
	mysqli_query($con,'set names utf8');      //設定編碼
	mysqli_query($con,'set character_set_client=utf8');
	mysqli_query($con,'set character_set_results=utf8');

	$sql = 'select * from friendslist where 1';      //建立sql語句
	$result = $con->query($sql);        //執行sql語句

	if($result->num_rows>0){               //判斷結果條數
		for($i=0,$jsonInfo=[]; $row=$result->fetch_assoc();$i++){
			$jsonInfo[] = $row;        //拼湊結果
		}
		echo json_encode($jsonInfo);      //json返回
	}
}

(2)sql查詢語句
語法:$sql = "select 【資訊】 from 【哪張表】 where 【查詢條件】";
(3)sql插入語句
語法:

$sql = "insert into 表名(欄位1,欄位2,...) values ('值1','值2',...)";
	    $sql = "insert into 表名 values(值1,值2,...)";

(4)sql修改語句
語法:$sql = “update 表名 set 欄位1='新值1',… where id=$id",…;
注意:修改的關鍵詞是update,而不是updata!!
注意:where後面的條件可以和修改的內容相同。

(5)sql刪除語句
語法:$sql = 'delete from 表名 where 條件';

6.html與php+MySQL完成前後端互動

前端關鍵部分程式碼:【ajax請求】

    $.ajax({
        	type:'post',
        	url:'add.php',
        	dataType:"json",
        	data:{
        		friendsName:$('.fname').val(),
        		…
        	},
        	success:function(data){console.log(data);},
        	error:function(error){console.log(error);}
});

後臺部分程式碼:【php接受ajax request,並通過echo給出response】

$con = mysqli_connect('localhost','root','','frankdb');
$success = array("code" => "success");
$error = array("code" => "error");
if($con){
	mysqli_query($con,'set names utf8');
	mysqli_query($con,'set character_set_client=utf8');	
	mysqli_query($con,'set character_set_results=utf8');

	$fname = $_POST['friendsName'];
	…
	$result = $con->query("insert into friendslist values($fname,…)");
	if($result){
		echo json_encode($success);
	}
}else{
	echo json_encode($error);
}

7.登入流程

(1)將使用者輸入資訊傳送給後臺--------ajax請求實現
(2)後臺接收使用者傳送的內容--------php中的 P O S T _POST或 _GET物件獲取
(3)在資料庫中搜索目標條目--------sql查詢語句
(4)返回前端response--------echo語句返回json_encode內容