繁体   English   中英

如何使用 PHP 获取 MySQL 表中行的排名以及如何将其存储到单独的变量中?

[英]How to get the rank of a row in a MySQL table using PHP and how to store it into a separate variable?

我一直在 PHP 中编写 cron 作业的脚本,该脚本应该连接到文本文件,分别使用 Java 获取写入其中的参与者 ID,并在单独的文本文件中返回有关该参与者的详细信息。 该参与者的详细信息应该是他们在其他参与者中的积分、数量和排名(这是使用各自参与者获得的积分获得的)。

这是我到目前为止编写的代码:

<?php

//connect to mysql database procedurally
$conn = mysqli_connect("localhost","root","","anka");

if(!$conn){
    echo "Connection error" . mysqli_connect_error("localhost","root","","anka");
}

$participantid = 0;
$participantid = fopen('performancerequests.txt',"r") or die("Request not taken.");
$content = fread($participantid, filesize("performancerequests.txt"));
file_put_contents("performancerequests.txt","");


//should return rank, points, products left(quantity) 
$sql1 = "SELECT points from participants where id='$content'";
$sql2 = "SELECT quantity from products where participant_id='$content'";
$sql3 = "SELECT points, ROW_NUMBER() OVER( ORDER BY points ) RowNumber from participants where id='$content'";

$result1 = mysqli_query($conn, $sql1);
$result2 = mysqli_query($conn, $sql2);
$result3 = mysqli_query($conn, $sql3);

while ($row1 = $result1->fetch_assoc()) {
    $points = $row1['points'];
}

while ($row2 = $result2->fetch_assoc()) {
    $quantity = $row2['quantity'];
}

while ($row3 = $result3->fetch_assoc()) {
    $rank = $row3['rank'];
}


$handle = fopen("performance.txt", "w") or die("File does not exist.");
if(fwrite($handle,$content." "."Points: ".$points." "."Quantity: ".$quantity." "."Rank: ".$rank) == false ){
    echo "Error Writing.";
}

?>

有问题的表的代码也如下:

CREATE TABLE participants (
    id bigint(20),
    name varchar(255),
    password varchar(255),
    product varchar(255),
    DOB date,
    points int(11),    
    PRIMARY KEY(id)
);

CREATE TABLE products (
    id bigint(20),
    name varchar(255),
    quantity varchar(255),
    rate varchar(255),
    description varchar(255),
    FOREIGN KEY(participant_id) REFERENCES participants(id),    
    PRIMARY KEY(id)
);

但是当我测试并运行它时,它会返回警告,即变量 $rank 存在未定义的数组键。 并且在文本文件中,排名位也留空。

有没有办法解决这个问题?

您必须将查询中的别名与数组键匹配:

 $sql3 = 
"WITH ranked AS(
    SELECT id, points, ROW_NUMBER() OVER( ORDER BY points ) RowNumber 
    FROM participants
) SELECT * FROM ranked WHERE id='$content'";
    
while ($row3 = $result3->fetch_assoc()) {
    $rank = $row3['RowNumber']; // here changed
}

php代码在线

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM