(《Head First PHP & MySQL》學習記錄)
從PHP連接數據庫
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>report</title>
</head>
<body>
<h2>Aliens Abducted Me - Report an Abduction</h2>
<?php
$dbc=mysqli_connect("127.0.0.1","root","12345678") or die('Error connecting to MySQL server.');
mysqli_select_db($dbc,"aliendatabase");
$query="INSERT INTO aliens_abduction (first_name,last_name,when_happened,time_last,fang,anything_else,email) VALUES ('Henry','Stuart','3 days ago','2 hour','yes','I\'ve played with a dog, please contact me!','[email protected]')";
$result=mysqli_query($dbc,$query) or die('Error querying database.');
mysqli_close($dbc);
?>
</body>
</html>
第一步,用mysqli_connection()連接數據庫;
第二步,構造查詢串;
第三步,用mysqli_query()執行查詢;
第四步,用mysqli_close()關閉連接。
從表單向數據庫添加數據
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>report</title>
</head>
<body>
<h2>Aliens Abducted Me - Report an Abduction</h2>
<?php
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$when=$_POST['when'];
$timelast=$_POST['timelast'];
$fang=$_POST['fang'];
$anythingelse=$_POST['anythingelse'];
$email=$_POST['email'];
$dbc=mysqli_connect("127.0.0.1","root","12345678") or die('Error connecting to MySQL server.');
mysqli_select_db($dbc,"aliendatabase");
/*$query="INSERT INTO aliens_abduction (first_name,last_name,when_happened,time_last,fang,anything_else,email) VALUES ('Henry','Stuart','3 days ago','2 hour','yes','I\'ve played with a dog, please contact me!','[email protected]')";*/
$query="INSERT INTO aliens_abduction (first_name,last_name,when_happened,time_last,fang,anything_else,email) VALUES ('$firstname','$lastname','$when','$timelast','$fang','$anythingelse','$email')";
$result=mysqli_query($dbc,$query) or die('Error querying database.');
mysqli_close($dbc);
?>
</body>
</html>
其中有一個問題,mysqli_connect()函數中數據庫的位置填"localhost"會出現錯誤。
若將"localhost"改爲"127.0.0.1"則可成功運行。原因見以下兩個連接。看不懂。
http://segmentfault.com/q/1010000000320989
http://segmentfault.com/q/1010000000328531