我使用 php 在 html 页面中创建了一个通知列表。
我需要在单击列表项时加载相关数据。(例如:当单击“[customer_name]需要注册”时,它应该在单独的页面中加载该客户名下的所有其他数据)我有尝试使用以下代码但没有得到期望的结果。
您能帮我解决这个问题吗?
<?php
$dbc = mysqli_connect('localhost','root','','dashboard') or die(mysqli_connect_error(''));
function notification() {
global $dbc;
$query = "SELECT `customer_name` FROM `customer` WHERE `confirmation`IS NULL LIMIT 0, 30 ";
$result = mysqli_query($dbc,$query);
global $row;
while($row=mysqli_fetch_array($result))
{
echo"<a href='CusRegReport.php'>"."<i class='fa fa-users text-red'>"." ".$row['customer_name']." "."needs to register"."</i>"."</a>";
global $x;
$x = $row['customer_name'];
}
}
function details(){
global $x;
$sql = "SELECT * FROM `customer` WHERE `customer_name` = '$x'";
$r = mysqli_query($dbc,$sql);
while($line=mysqli_fetch_array($r))
{
$d = "<br/>".$line['customer_name']."<br/>".$line['ad_line_one']."</a>";
}
}
?>
最佳答案
我刚刚稍微修改了一下代码。
index.php
:在这里您将显示通知。
<?php
$dbc = mysqli_connect('localhost','root','','dashboard') or die(mysqli_connect_error(''));
function notification(){
global $dbc;
$query = "SELECT `customer_id`, `customer_name` FROM `customer` WHERE `confirmation`IS NULL LIMIT 0, 30 ";
$result = mysqli_query($dbc,$query);
while($row=mysqli_fetch_array($result))
{
echo "<a href='CusRegReport.php?id=" . $row['customer_id'] . "'><i class='fa fa-users text-red'> " . $row['customer_name'] . " needs to register</i></a>";
}
}
?>
<!doctype html>
<html>
<body>
<?php notification(); ?>
</body>
</html>
<小时/>
CusRegReport.php
:在这里您将显示具有特定 ID 的客户的详细信息。
<?php
$dbc = mysqli_connect('localhost','root','','dashboard') or die(mysqli_connect_error(''));
function details(){
global $dbc; // we need this in all our functions. Then only we will be able to do the db operations within the function
$id = $_GET['id']; // we are using the id that was passed in the URL
$id = $mysqli->real_escape_string( $id ); // clean the id that the user passed via url, so that we could use it in our SQL query. Otherwise it is unsafe to use directly because it can lead to SQL injections
$sql = "SELECT * FROM `customer` WHERE `customer_id` = '$id'";
$r = mysqli_query($dbc,$sql);
while($line=mysqli_fetch_array($r))
{
echo "<br/>" . $line['customer_name'] . "<br/>" . $line['ad_line_one'] . "</a>";
}
}
?>
<!doctype html>
<html>
<body>
<?php details(); ?>
</body>
</html>
<小时/>
要记住的事情:
您已声明 mysqli 对象
$dbc
在页面的最顶部。因此,如果您想使用该对象从函数内部访问数据库,则需要使用global
关键字如下:global $dbc;
避免过度使用关键字
global
。您正在使用它来声明每个变量!不需要。当您回显
<a>
时指向客户详细信息页面的链接,包括customer_id
在?
之后的网址中。我们这样传递的数据将在$_GET
中提供。结果页面上的数组。始终尝试使用整数值来识别客户。因为不止一位客户可以有相同的名字!由于您的数据库中已经有了客户的详细信息,我相信您已经使用了
PRIMARY KEY
对于该表,可能是customer_id
, 我猜。所以就用那个吧。避免不必要的串联。稍后可能会给您带来困惑。在你的第一个
echo
行,即使您只是连接字符串,您也使用了很多连接。在 SQL 查询中使用从用户接受的数据之前,请尝试对其进行转义。因为用户提供的数据可能会引起sql注入(inject)攻击。因此,请务必清理用户输入。
这些对您来说只是快速的基本操作。
希望能有所帮助。 注意:我只是稍微修改了你的代码。没有测试或做任何事情。
关于php - 如何使用php创建通知列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33699326/