简体   繁体   English

需要帮助拉起这个MySQL查询在PHP

[英]Need help pulling up this Mysql Query in php

I have a simple scenario but not getting it to work. 我有一个简单的场景,但是无法正常工作。 I need to pull up a value for column 'fee' specified in Mysql Database according to two values. 我需要根据两个值为Mysql数据库中指定的列“ fee”上拉一个值。

我的当前表格结构和值

I want to get the value for 'fee' if I specify an amount between columns 'from' and 'to' Example: if amount is 95, the value for row 'fee' should be 0.99. 如果要在列“ from”和“ to”之间指定一个量,我想获取“ fee”的值。例如:如果数量为95,则行“ fee”的值应为0.99。

I tried to use traditional method previously like below but now I would like MYSQL query method. 我曾尝试像下面那样使用传统方法,但现在我想使用MYSQL查询方法。 Please help. 请帮忙。

if ($amount < 100) {
$fee = '0.99';
}
else if ($amount > 100 && $amount < 500) {
$fee = '1.99';
}
else if ($amount < 500 && $amount < 1000) {
$fee = '2.99';
}
else if ($amount < 1000 && $amount < 10000) {
$fee = '4.99';
}
else if ($amount > 10000) {
$fee = '9.99';
}

A Sample PHP Code: PHP示例代码:

<?
include "dbconnect.php";

$post_amount = $_POST["amount"];

$sql = "SELECT fee FROM fees WHERE from < '$post_amount' AND to >     '$post_amount'     LIMIT 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array( $result )) {
$fee = $row["fee"];
}
echo "Posted Amount is $post_amount and Fee is $fee";

?>

If I get your question, you need the SQL query. 如果我有您的问题,则需要SQL查询。

You can use > and < signs: 您可以使用>和<符号:

"SELECT fee FROM tablename WHERE from < '$amount' AND to > '$amount' LIMIT 1"

Or you can use BETWEEN ( How to search between columns in mysql ): 或者您可以使用BETWEEN( 如何在mysql中的列之间搜索 ):

"SELECT fee FROM tablename where '$amount' BETWEEN from AND to LIMIT 1"

Two more things: 还有两件事:

  1. You'll need to sanitize $amount variable before using it in the query 您需要先清理$ amount变量,然后才能在查询中使用它
  2. from and to are MySQL Reserve Words and should not be used as column names fromtoMySQL保留字 ,不应用作列名

MySQL有一个很棒的运算符,称为BETWEEN

"SELECT `fee` FROM `table` WHERE ".floatval($amount)." BETWEEN `from` AND `to`"

You just had problem in > and < all other things are fine in ur code there no need for other function to check it from database table. 您在> and <只是有问题,在您的代码中其他所有内容都没问题,不需要其他功能即可从数据库表中进行检查。

I have checked it with this : 我已经检查过了:

$amount = 250;

if ($amount < 100) {
    $fee = '0.99';
} else if ($amount > 100 && $amount < 500) {
    $fee = '1.99';
} else if ($amount > 500 && $amount < 1000) {
    $fee = '2.99';
} else if ($amount > 1000 && $amount < 10000) {
    $fee = '4.99';
} else if ($amount > 10000) {
    $fee = '9.99';
}

echo $fee;

Its works fine. 它的作品很好。

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

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