将PHP变量分配给SQL查询的结果

时间:2014-01-27 16:04:25

标签: php mysql sql

基本上我要做的是为SQL语句的结果分配一个变量。

在此示例中,我想计算当前登录的客户ID在名为预订的表中出现的次数。如果此计数为5或大于$ apply_discount = 50。这可以在页面后面用来折扣百分比金额。

我已经尝试了几天,但我对使用SQL和PHP非常不熟悉。

这是我到目前为止所做的:

<?php 
    $numofbookings = " number of times {$_SESSION['login']} appears in the booking table " //this is where im unfamiliar with the syntax
    // sql statement that counts how many times the currently logged in customers  id     {$_SESSION['login']} appears in the booking table 
    // database connection is done earlier on in the page with a db_connection.php include
    // table is called "bookings"
    // col that contains customer ids (which comes from {$_SESSION['login']} ) is called customer_id
?>


<?php 
    if $numofbookings =("5>")
    {
        $apply_discount=("50");
    }
    else
    {
        $apply_discount=("0");
    }
    // if the customer has 5 of more bookings then $apply_discount is 50,
    // this can be used later on to discount the % amount from the base price
?>

<?php
    $newprice = $base_price * ((100-$apply_discount) / 100); // calculation at bottom of page
?>

1 个答案:

答案 0 :(得分:0)

首先,您需要查询数据库以计算满足您要求的行数:

$mysqli = new mysqli('hostname', 'username', 'password', 'database');

$stmt = $mysqli->prepare("SELECT COUNT(*) FROM bookings WHERE customer_id = ?")

$stmt->bind_param('i', $_SESSION['login']);

$stmt->execute();

$stmt->bind_result($numofbookings);

$stmt->fetch();

$stmt->close();

然后你需要修复折扣逻辑:

if ($numofbookings > 5)
{
  $apply_discount = 50;
}

else
{
  $apply_discount = 0;
}

此外,在您使用会话时,您需要确保session_start();包含在文件顶部,否则$_SESSION将不确定。

您应该查看mysqliPDO扩展程序,MySQL文档以及PHP的{​​{3}}和control structures