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

将PHP变量分配给SQL查询的结果,php,mysql,sql,Php,Mysql,Sql,基本上,我要做的是为SQL语句的结果分配一个变量 在本例中,我想计算当前登录的客户id在名为bookings的表中出现的次数。如果此计数为5或大于$apply\u折扣=50。这可以在页面的稍后部分用于折扣百分比金额 我已经尝试了几天了,但是我对在PHP中使用SQL非常不熟悉 这就是我到目前为止所做的: <?php $numofbookings = " number of times {$_SESSION['login']} appears in the booking table

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

在本例中,我想计算当前登录的客户id在名为bookings的表中出现的次数。如果此计数为5或大于$apply\u折扣=50。这可以在页面的稍后部分用于折扣百分比金额

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

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

<?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
?>

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

$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;
}
此外,在使用会话时,您需要确保会话启动;包含在文件顶部,否则$\u会话将未定义


您应该查看or扩展名、文档以及PHP和。

如果您对字符串进行计算并且涉及到金钱,最好使用二进制计算器:-ssidefine:如果$numfobookings>5而不是$numfobookings=5>您应该这样做,您引用的数字将不会被视为整数。@MichaelRushton,我想他希望有人为他编写所有的查询和代码。如果不知道表结构和样本值,这将很难得到帮助。我愿意给出提示和指导,但我不会写全部内容,特别是因为他似乎不知道自己在用PHP做什么,根本不知道。OP希望您/我们能够一如既往地填补空白@MichaelRushton向Michael发布了同样的消息,可能是在同一时间,如果不是在毫秒之前,lol@PhilPerryMaybe添加了一条说明,表明会话开始;将在所有使用的文件中要求使用我怀疑OP在PHP/SQL方面的经验。只是补充一点。bind_参数'i',$会话['login']中的i-会话是一个相当长的字母数字字符串。