phpstorm是一款php集成開發環境軟件,集成了很多功能,不但有強大的代碼編輯及調試功能,還能連接數據庫。本文寫的就是如何用phpstorm來建立訪問wampserver數據庫,查詢輸出數據,方便我們開發工作。
1、新建數據庫
方法一:點擊wampserver的綠色圖標,直接選擇phpMyAdmin選項,進入wampserver數據庫
方法二:點擊wampserver的綠色圖標,選擇Localhost選項,進入wampserver簡單頁面,然后導航輸入(http://localhost/phpmyadmin),進入wampserver數據庫
選擇中文編碼
點擊NEW新建數據庫,輸入新建的數據庫名點擊創建
創建數據庫成功,點擊左側目錄里創建出來的數據庫,添加並創建表選擇執行
創建自己的表結構並選擇保存(A_I的意思是自增序列,一般id都要選擇這個)
選擇插入數據, 錄入相關信息並選擇執行
選擇瀏覽來查看我們錄入的數據
好,數據庫部分我們就完成啦!
2、連接數據庫
代碼第一行就是連接數據庫
PHP代碼如下:
<?php //mysql:host=主機名,port=端口號,dbname=數據庫名,root為權限,該句連接數據庫 $link=new PDO("mysql:host=localhost;port=3306;dbname=db","root",""); $link->query("set names utf8");//為中文編碼集 $arr=$link->query("select * from users");//查詢users表中所有數據 while ($row=$arr->fetch()){//每一次讀取arr中的一條數據 $json[]=$row; } $link=null;//銷毀link節省資源 echo json_encode($json);//返回為json格式
3、測試訪問數據庫
HTML代碼如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <table> <thead> <th>用戶名</th> <th>密碼</th> <th>昵稱</th> </thead> <tbody id="tbody"> </tbody> </table> </div> <template id="temp"> <tr> <td>{{name}}</td> <td>{{pwd}}</td> <td>{{nickname}}</td> </tr> </template> </body> <script src="jquery-2.1.3.js"></script> <script> var temp=$('#temp').html(); $.getJSON('connect.php',function (arr) { arr.forEach(function (el) { $('#tbody').append(temp.replace("{{name}}",el.name).replace("{{pwd}}",el.pwd) .replace("{{nickname}}",el.nickname)) }) }) </script> </html>
運行結果: