PHP使用大于和小于在MySQL中选择值


PHP Select Value in MySQL Using Greater Than and Less Than

我一直在绞尽脑汁,试图得到一些看起来简单的东西。我有一个表"重量"。Weight有3列:"shipping_to"、"shipping_from"answers"shipping.cost"。

Shipping_to和Shipping_from是重量值,如果该值大于或等于X且小于或等于X,则运输成本保持运输成本。

我已经用无数种不同的方式写了这篇文章,但对我来说,这是行不通的。

更新时间:脚本的工作方式"有点",但它从不返回1的成功响应,也从不输入X的值,即使我已经手动将这些值放入MySQL数据库中。

PHP脚本:

if($The_Function=="SHIPPING_COST"){
    $response = array();
    require_once __DIR__ . '/db_connect.php';
    $con = new DB_CONNECT();
    $ship_weight = 1;

    $result = mysql_query("SELECT * FROM weight WHERE from_weight >= '$ship_weight' AND to_weight <= '$ship_weight'");
    if(!empty($result)){
        if (mysql_num_rows($result) > 0) {
            $response["userID"] = array();
            while ($row = mysql_fetch_array($result)) {
                $custID = array();
                $custID["shipping_cost"] = $row["shipping_cost"];
                array_push($response["userID"], $custID);
            }
            $response["success"] = 1;
            echo json_encode($response);
        }else {
            $response["success"] = 0;
            $response["message"] = "No shipping found";
            echo json_encode($response);
        }
    }else {
        $response["success"] = 0;
        $response["message"] = "No shipping found";
        echo json_encode($response);
    }
}

错误发生在查询本身。我所要做的就是给最后一列一些可以比较的东西,所以我只是再次添加了$ship_weight。这是代码。

$result = mysql_query("SELECT * FROM weight WHERE '$ship_weight' >= from_weight AND  '$ship_weight' <= to_weight");

我认为问题是$result永远不会是empty()

如果查询有效,则If将是resource handle,如果查询失败,则为false

所以试试这个:

$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '$ship_weight' AND to_weight <= '$ship_weight'");
if($result !== FALSE){
    if (mysql_num_rows($result) > 0) {
        $response["userID"] = array();
        while ($row = mysql_fetch_array($result)) {
            $custID = array();
            $custID["shipping_cost"] = $row["shipping_cost"];
            array_push($response["userID"], $custID);
        }
        $response["success"] = 1;
        echo json_encode($response);
    }else {
        $response["success"] = 0;
        $response["message"] = "No shipping found";
        echo json_encode($response);
    }
}else {
    $response["success"] = 0;
    $response["message"] = "No shipping found";
    echo json_encode($response);
}

这是代码的复制粘贴吗?如果是这样的话,看看这一行:

$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '$ship_weight' AND to_weight <= '$ship_weight'");

PHP正在考虑将$ship_weight变量作为字符串的一部分。更改为:

$result = mysql_query("SELECT * FROM weight WHERE from_weight >= '".$ship_weight."' AND to_weight <= '".$ship_weight."'");

此外,mysql_*也被弃用。看看mysqli_*扩展。