我写过类似
的内容$sql = "SELECT `id`, `name`, `comment`, `time` FROM `comments` id='".$_GET['id']."'";
但它仍然无法正常工作,未定义ID,我该怎么办?
<?php
require 'head.php';
require 'navbar.php';
require 'config.php';
if(isset($_COOKIE['taxi'])){
echo '<div class="container" style="margin-top: 10%;">
<div class="col-lg-4"></div>
<div class="panel panel-default col-lg-4">
<div class="panel-heading">Submit Your Comments</div>
<div class="panel-body">
<form method="post" action="comment.php">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" name="name" class="form-control" id="exampleInputEmail1" placeholder="name">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Comment</label>
<textarea name="comment" class="form-control" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
</form>
</div>
</div>
<div class="col-lg-4"></div>
</div>';
$sql = "SELECT `id`, `name`, `comment`, `time` FROM `comments`";
$query = $con->query($sql);
while ($row = mysqli_fetch_assoc($query))
{
echo "<div class='container'>";
echo "<div class='col-lg-4'></div>";
echo "<div class='col-lg-4' style='margin-top:5%;'>";
echo "<p>Name: " . $row['name'] . "</p>";
echo "<p>Comment: " . $row['comment'] . "</p>";
echo "<p>Time: " . $row['time'] . "</p>";
echo "</div>";
echo "<div class='col-lg-4'></div> ";
echo "</div>";
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql = "INSERT INTO `comments`(`id`, `name`, `comment`, `time`) VALUES (NULL,'$name','$comment',CURRENT_TIMESTAMP)";
$query = $con->query($sql);
}
}
else{
echo "<p style='margin-top:5%; text-align:center; font-size:40px;'>Access denied to write comment, but you can see comments</p>";
echo "<a href='login.php'><p style='text-align:center;'> Sign in to write a comment </p></a>";
$sql = "SELECT `id`, `name`, `comment`, `time` FROM `comments`";
$query = $con->query($sql);
while ($row = mysqli_fetch_assoc($query))
{
echo "<div class='container'>";
echo "<div class='col-lg-4'></div>";
echo "<div class='col-lg-4' style='margin-top:5%;'>";
echo "<p>Name: " . $row['name'] . "</p>";
echo "<p>Comment: " . $row['comment'] . "</p>";
echo "<p>Time: " . $row['time'] . "</p>";
echo "</div>";
echo "<div class='col-lg-4'></div> ";
echo "</div>";
}
}
?>
答案 0 :(得分:0)
问题是A:
您的数据库中没有id
列,因此当您尝试使用此行选择id
时会引发错误:
`$sql = "SELECT `id`, `name`, `comment`, `time` FROM `comments`";`
潜在问题B:
您的id
列已设置为数据库中的主键。这意味着id
列会为每个插入的记录自动递增1。但是,当您重新插入新行时,我会尝试将id
设置为NULL
:
$sql = "INSERT INTO `comments`(`id`, `name`, `comment`, `time`) VALUES (NULL,'$name','$comment',CURRENT_TIMESTAMP)";
尝试将其更改为:
$sql = "INSERT INTO `comments`(`name`, `comment`, `time`) VALUES ('$name','$comment',CURRENT_TIMESTAMP)";
潜在问题C(最有可能):
您在加载页面时未设置$_GET['id']
参数。这是您在许多网址中看到的?id=x
。
正如其他人提到的那样,你的查询是可注射的,我知道你说这只是本地的,但从关闭中养成良好的习惯是好的。