wamp+win10: php連線Mysql, delete update insert 詳細操作步驟
阿新 • • 發佈:2019-02-04
一、新建資料庫使用者
進入phpmyAdmin
- 點選“使用者”(Users)
點選使用者列表下方的“新增使用者”(Add user)
如下圖操作
點選“執行”(“Go”)之後,可以看到增加了user使用者。
注意:Grant必須為Yes,否則無法連線資料庫。如果為No,點選右邊“Edit Privileges” ,在上圖中的Administration下的GRANT前面框框打勾,再點選”Go”或”執行”按鈕。
二、寫index.php檔案
1、在wamp的www目錄下,新建資料夾,命名為test。在test資料夾下,新建index.php檔案,內容為:
<html>
<head>
<title>php連線mysql資料庫</title>
</head>
<body>
<?php
$dbHostname = "localhost";
$dbUsername = "user";
$dbPassword = "123455";
$dbName = "test";
$dblink = mysql_connect($dbHostname , $dbUsername, $dbPassword);
if ($dblink) {
echo "連線成功!";
}
else {
echo "連線失敗!";
}
?>
</body>
</html>
2、在瀏覽器位址列,輸入”localhost:8080/test(我localhost配置監聽的是8080埠),回車。可以看到顯示連線成功。
三、新建資料庫並建表。注意選擇的編碼格式,連線資料庫時需要匹配。
此時可以看到已經新建了dbtest1資料庫
- 點選dbtest1, 輸入表名和列數,然後點選右下角的“執行”(“GO”)。
- 然後一次輸入各行各列的資訊。我輸入完之後是這樣的表:
- 這個時候表還是空的,需要插入資料。點選Insert:
- 我插入了兩條記錄:另一條是(2,b,2,女,2017-01-02)
- 也可以通過SQL語句來插入:
-
- 這時候點選student表,檢視剛才插入的3條記錄:
-
五、php操作Mysql
分5個步驟:
1、連線資料庫系統(主機名,使用者名稱,密碼等)
2、設定編碼集
3、選擇要連線的資料庫
4、操作
5、關閉資料庫
<html>
<head>
<title>php連線mysql資料庫</title>
</head>
<body>
<?php
$dbHostname = "localhost";
$dbUsername = "user";
$dbPassword = "xushuai";
$dbName = "dbtest1";
$dblink = mysql_connect($dbHostname, $dbUsername, $dbPassword) or
die("Could not connect:".mysql_error());
//設定字符集,必須跟資料庫設定相匹配
mysql_query("set names 'GBK'");
//選擇資料庫
mysql_select_db($dbName);
function _print($dblink){
$sql_1 = "select * from student";
$result = mysql_query($sql_1,$dblink);
while($row = mysql_fetch_array($result)){
echo "<div style =\"height:24px;line-height:24px;font-weight:bold;\">";
echo "id=".$row['id']." name=".$row['name']." age=".$row['age']." gender=".$row['gender']." class=".$row['class']."<br/>";
echo "</div>";
}
}
echo "<br/><b>select * from student:</b>";
_print($dblink);
$sql_2 = "insert into student(id,name,age,gender,class) values('4','d','4','男','2017-01-04');";
mysql_query($sql_2,$dblink);
echo "<br/><b>insert into student(id,name,age,gender,class) values('4','d','4','男','2017-01-04'):</b>";
_print($dblink);
$sql_3 = "delete from student where id = 4;";
mysql_query($sql_3,$dblink);
echo "<br/><b>delete from student where id = 4:</b>";
_print($dblink);
$sql_4 = "update student set name = 'e' where id = 1;";
mysql_query($sql_4,$dblink);
echo "<br/><b>update student set name = 'e' where id = 1:</b>";
_print($dblink);
mysql_close($dblink);
?>
</body>
</html>
執行如上程式碼,在位址列輸入地址,可以看到以下結果: