【问题标题】:Assigning a PHP variable to the results of an SQL query将 PHP 变量分配给 SQL 查询的结果
【发布时间】:2014-01-27 16:04:24
【问题描述】:

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

在此示例中,我想计算当前登录的客户 ID 在名为 bookings 的表中出现的次数。如果此计数为 5 或更多,则 $apply_discount=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
?>

【问题讨论】:

  • 如果你对字符串进行计算并且涉及金钱,最好使用二进制计算器:-S
  • 旁注:您应该使用if ($numofbookings &gt;5) 而不是if $numofbookings =("5&gt;") 您引用的数字不会被视为整数。
  • @MichaelRushton,我认为他希望有人为他编写所有查询和代码。在不知道表结构和样本值的情况下,这将很难提供帮助。我愿意提供提示和指导,但我不会写完整的东西,尤其是因为他似乎不知道他在用 PHP 做什么。
  • 没有。 OP 的“希望”您/我们将“填补空白”,事实上。 @迈克尔拉什顿
  • 发布了同样的事情(给迈克尔),可能是在同一时间,如果不是“毫秒”,哈哈@PhilPerry

标签: php mysql sql


【解决方案1】:

首先你需要查询数据库,统计出符合你要求的行数:

$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 文档以及PHPcontrol structuressessions

【讨论】:

  • 可能会添加一个注释以表明在所有使用的文件中都需要session_start();。 ;-) 我怀疑 OP 在 PHP/SQL 方面的经验。
  • 只是迈克尔的一个补充说明。 bind_param('i', $_SESSION['login']) 中的 i - 会话是一个相当长的字母数字字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
相关资源
最近更新 更多