【发布时间】:2015-12-15 17:36:03
【问题描述】:
我对 PHP/SQL 编码相当陌生,我完全不知道为什么这种编码不起作用。数据库本身是由我的大学制作的,所以我只是想连接它(我不确定我是否能够泄露细节,所以我把连接编码去掉了。我处于基础水平,所以繁重的技术语言会让我头疼,但任何建议都将不胜感激!
我正在尝试将链接到 PHP 文件的表单中的结果插入到数据库表中。我不确定是否需要在 PHP 文件中添加任何内容来说明这一点?但这是我的代码:
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Connect to database
$sql = "SELECT runnerid, position, eventid, date, finishtime, categoryid, agegrade, pb FROM Results";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
{
echo "<table>";
echo '<table border=1><tr><th>Runner ID</th><th>Position</th><th>Event ID</th><th>Date</th><th>Finish Time</th><th>Category ID</th><th>Age Grade</th><th>Personal Best</th></tr>';
echo "<tr><td>";
echo $row['runnerid'];
echo "</td><td>";
echo $row['position'];
echo "</td><td>";
echo $row['eventid'];
echo "</td><td>";
echo $row['date'];
echo "</td><td>";
echo $row['finishtime'];
echo "</td><td>";
echo $row['categoryid'];
echo "</td><td>";
echo $row['agegrade'];
echo "</td><td>";
echo $row['pb'];
echo "</td>
</tr>";
}
echo "</table>";
}
} else {
echo "0 results";
}
$sql = "INSERT INTO Results VALUES ('$_POST[runnerid]', '$_POST[position]' '$_POST[eventid]' '$_POST[date]' '$_POST[finishtime]' '$_POST[categoryid]' '$_POST[agegrade]' '$_POST[pb]')";
$result = $conn->query($sql);
if (!$result) {
die('Could not insert data' . mysql_error());
}
$conn->close();
?>
我什至尝试了没有$_POST 编码的代码来添加新数据,但这也不起作用。
【问题讨论】:
-
die()语句是否有错误? -
您在查询中的值之间缺少逗号。
runnderid后面有一个,但其他人都没有。 -
请参阅以下链接 php.net/manual/en/mysqli.error.php 和 php.net/manual/en/function.error-reporting.php 并将其应用于您的代码。您还将 MySQL 函数与
mysql_error()混合使用,它应该读作mysqli_error($conn)。不发布与此相关的 HTML 表单,让我们都在猜测。 检查错误。 -
值得一提的是,您应该使用 PDO 而不是 mysqli;它更便携,更易于使用。