客户端按下按钮时在PHP中计数器

时间:2015-09-05 14:29:33

标签: php mysql counter

我在php中有这部分代码。当玩家在客户端按下按钮(使用ajax)时,我希望我的数据库显示下一条记录。但我不会。

if(isset($_POST['req'])){

$counter++;

$sql = "SELECT question FROM mytable WHERE id = $counter";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
    echo $row["id"]." ". $row["question"]. " " . "<br>";
}
} else {
 echo "0 results";
}

}

2 个答案:

答案 0 :(得分:0)

简单的方法是在Ajax请求中发送当前id。增加它然后用它来从数据库中提取下一个问题

答案 1 :(得分:0)

我建议将你的计数器存放在一个会话中。然后,每当玩家执行此操作时,您可以像下一样给他们下一行: -

session_start();


if(isset($_POST['req'])){

    if ( ! isset($_SESSION['counter']) ) {
        $_SESSION['counter'] = 1;
    } else {
        $_SESSION['counter'] = $_SESSION['counter'] + 1;
    }

    $sql = "SELECT question FROM mytable WHERE id = {$_SESSION['counter']}";
    $result = $conn->query($sql);

    if ( ! $result ) {
        // log error to error log
        error_log(print_r($conn->errorinfo(),true), 3, 'app_error.log');
        echo "Temporary database issues, please try again later";
        header('Location: error_page.php');
        exit;
    }

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        echo $row["id"]." ". $row["question"]. " " . "<br>";
    } else {
        echo "0 results";
    }
}