问题描述
<?PHP
include ("../dataconnection.PHP");
if(isset($_GET['sub']))
{
if(isset($_POST['name']))
$name = $_POST['name'];
if(isset($_POST['content']));
$content = $_POST['content'];
$query = "INSERT INTO testimonial (testi_name,testi_content) VALUES ('$name','$content')";
$result = MysqLi_query($connect,$query);
?>
<script>
alert("Your review has been submitted!");
</script>
<?PHP
header("Refresh:0");
}
$getTesti = "SELECT * FROM testimonial ORDER BY testi_name ASC";
$result = MysqLi_query($connect,$getTesti) or die(MysqLi_error($connect));
$row = MysqLi_fetch_assoc($result);
?>
<?PHP foreach($row as $review):?>
<div class="Box">
<h3><?PHP htmlspecialchars($review['testi_name'],ENT_QUOTES); ?></h3>
<?PHP htmlspecialchars($review['testi_content'],ENT_QUOTES); ?>
</div>
<?PHP endforeach; ?>
嗨,我遇到了第二个编码显示非法字符串偏移“testi_name”的问题。我尝试阅读已解决的其他问题,但我仍然无法理解。我从我的 sql 中得到了“testi_name”。请告诉我有什么问题,因为我是 PHP 的初学者。谢谢,非常感谢您的帮助。
它甚至循环了 3 次,尽管我的 sql 中只有 1 行 [1]:https://i.stack.imgur.com/C8hhd.png
解决方法
$row
只是第一行结果,不是所有结果。因此,您要遍历第一行中的列,而不是所有行。
您还应该使用准备好的语句,而不是将变量替换到 SQL 中。
代码应该是:
<?php
include ("../dataconnection.php");
if(isset($_GET['sub']))
{
$content = $_POST['content'];
if(!empty($name)&& !empty($rate)&& !empty($content))
{
$query = "INSERT INTO testimonial (page_id,testi_name,testi_content,testi_rating) VALUES (?,?,?)";
$stmt = mysqli_prepare($connect,$query);
mysqli_stmt_bind_param($stmt,"ssss",$page,$name,$content,$rate);
mysqli_stmt_execute($stmt);
?>
<script>
alert("Your review has been submitted!");
</script>
<?php
header("Refresh:0");
}
}
$getTesti = "SELECT * FROM testimonial ORDER BY testi_name ASC";
$result = mysqli_query($connect,$getTesti) or die(mysqli_error($connect));
while ($row = mysqli_fetch_assoc($result)): ?>
<div class="box">
<h3><?php htmlspecialchars($row['testi_name'],ENT_QUOTES); ?></h3>
<?php htmlspecialchars($row['testi_content'],ENT_QUOTES); ?>
</div>
<?php endforeach; ?>