基本上我有一个数据库和一个名为 apartments 的表,我正在使用此代码在一页上输出内容:
$connect = mysqli_connect("localhost","root","","db_dice");
$query = "SELECT * FROM apartment ORDER BY ID DESC";
$records = mysqli_query($connect,$query);
//check connection
if ($connect->connect_error) {
die('Connection failed: ' . $conn->connect_error);
echo 'err';
}
while($show=mysqli_fetch_array($records)){
echo '<div class="div-recentupdate" style="background-color:white">';
echo '<a href="apartment.php">'.$show['apartment name'].' Bedroom:'.$show['bedroom'].' Price:$'.$show['price'].' <br></a>';
echo '</div>';
}
问题很简单(我习惯了mvc所以这就是为什么我不知道这个,对不起)。
我想要的是在另一个名为 apartment.php
的页面上输出数据库的内容(公寓名称、卧室等)
我想我应该使用
<a href="apartment.php?id=(variable of the id of the chosen link)">
但我不知道怎么做。
请帮忙。
最佳答案
"I think I'm supposed to use
<a href apartment.php?id= (variable of the id of the chosen link)>
"
更正,并确保 =
后没有空格符号。
首先我们需要使用 ?id
为了从数据库中获取记录(并传递到第二页),同时将其分配给 id
行使用:
-
$show['ID']
在href
里面在您的第一页中使用您发布的现有代码。
然后在第二页上,您将使用 WHERE
使用从变量中获取的 id 的子句并检查赋值是否已设置。
旁注:您的 ID
必须是 int
键入以使其正常工作。
在您的第一页中:
替换当前的 href
正在回显的行:
echo '<a href="?id='.$show['ID'].'">'.$show['apartment name'].' Bedroom:'.$show['bedroom'].' Price:$'.$show['price'].' <br></a>';
然后在你的第二页:
旁注:使用 (int)
对于 (int)$_GET['id']
使它成为一个安全数组。
if(isset($_GET['id'])){
$id = (int)$_GET['id'];
$query_fetch = mysqli_query($connect,"SELECT * FROM apartment WHERE ID = $id");
while($show = mysqli_fetch_array($query_fetch)){
echo "ID: " . $show['ID'] . " " . $show['apartment name']. " Bedroom:".$show['bedroom']." Price:$".$show['price']." <br></a>";
} // while loop brace
} // isset brace
else{
echo "It is not set.";
}
另一个旁注:
您还可以使用以下内容代替 (int)
:
$id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
脚注:
我注意到你这里有空间$show['apartment name']
在 apartment
之间和 name
.
请注意这一点,因为如果在没有使用标记转义的查询中使用空格会导致问题。
即:这会失败并导致语法错误:
SELECT * FROM apartment WHERE ID = $id AND apartment name = 'apartment 101'
您需要注意并注意 apartment name
周围的刻度线姓名:
SELECT * FROM apartment WHERE ID = $id AND `apartment name` = 'apartment 101'
最好用下划线作为单词分隔符,只是说。
错误检查:
添加error reporting到您的文件的顶部,这将有助于查找错误。
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
旁注:显示错误只应在试运行中进行,绝不能在生产中进行。
以及or die(mysqli_error($connect))
至 mysqli_query()
.
引用资料:
我发现的另一件事是,您在这里使用了不正确的变量:
$conn->connect_error)
应该是$connect
,而不是 $conn
.
然后是你的echo"err";
永远不会发生,因为你已经使用了die()
.
来自手册:
此语言结构等同于 exit()。 http://php.net/manual/en/function.exit.php
"exit — Output a message and terminate the current script"
关于php - 从数据库中获取 id 并在另一个页面中显示内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35393472/