写入和读取MySql数据库的简单PHP代码。从在phpMyAdmin中手动输入的两行数据开始,然后通过PHP代码插入一个新行,当读回数据库内容时,一切都很好(见下文)。
然而,当在phpMyAdmin上检查数据库时,新行已插入三次而不是一次。有什么想法吗?
PHP代码:
<?php
$con = mysqli_connect("localhost","root","password","database");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error() . "<br>";}
else{
echo "Connected to MySQL okay <br>";}
// Test inserting new row into database
$str = "INSERT INTO sites (src_name, date, content) VALUES ('BBC', '2016-02-24 08:00:00', 'Bad weather in UK')";
$result = $con->query($str);
if ($result === TRUE){
echo "New record inserted successfully <br>";}
else{
echo "Error: ". $con->error . "<br>";}
// Test reading from database
$result = $con->query("SELECT * FROM sites");
if (mysqli_num_rows($result) > 0){
while($row = $result->fetch_assoc()){
echo "Source : " . $row["src_name"]. " - Date: " . $row["date"]. " - Content: " . $row["content"]. "<br>";}
}
mysqli_close($con);
?>