sql奇怪的数字字符串比较

时间:2015-04-03 10:17:59

标签: sql

在AsyncTask中,我传递了一个数字字符串w1:

params.add(new BasicNameValuePair("weight1", w1));

以下php脚本:

<?php

require("config.inc.php");
$query_params = null;

    $query = "  SELECT  onoma01 , epitheto01 , email01 ,username1,startPoli1, finalPoli1, 
    eidosmetaf1, weight1 , depDate1 , depTime1, tilefono01 
 FROM customer ,registration1 
 where   
 ( :sp1='empty' or customer.startPoli1 = :sp1) and 
 ( :w1='empty' or customer.weight1 < :w1) and 
  (  :em1='empty' or customer.eidosmetaf1 = :em1)  and 
  (  :fp1='empty' or customer.finalPoli1 = :fp1)  and 
  (  :dD1='empty' or customer.depDate1 = :dD1)  and 
 (customer.username1 = registration1.username01 )";    

    $query_params = array(

        ':sp1' => $_POST['startPoli1'],
        ':w1' =>  $_POST['weight1'],
        ':em1' => $_POST['eidosmetaf1'],      
        ':fp1' => $_POST['finalPoli1'],
       ':dD1' => $_POST['depDate1']               
    );

    try {
        $stmt   = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch (PDOException $ex) {

        $response["success"] = 0;
        $response["message"] = "Database Error2. Please Try Again!";
        die(json_encode($response));
    }

    $results = array();
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){

    $results[] = array(

     'onoma' => $row['onoma01'],
        'epitheto' => $row['epitheto01'],
        'email' => $row['email01'],
        'username1' => $row['username1'] ,
        'startPoli1' => $row['startPoli1'],
        'finalPoli1' => $row['finalPoli1'],
        'eidosmetaf1' => $row['eidosmetaf1'], 
        'weight1' => $row['weight1'] ,
        'depDate1' => $row['depDate1'],
        'depTime1' => $row['depTime1'],
        'tilefono1' => $row['tilefono01']   

    );  
    }

    echo json_encode(array('select_itin_results' =>$results));

?>

我要求数据库返回包含权重小于w1的行。我的数据库包括权重:

(100 , 200 , 350 ,2000)

当我设置w1 = 400时,它返回所有上面的数字,包括2000.它似乎比较两个数字的数字(400中的4个大于2000的2)。怎么会这样; (请注意,数据库中的权重列是varchar类型.T尝试更改为int而没有任何效果。此外,我尝试将$ _POST [&#39; weight1&#39;]作为一个int进行转换,但没有。谢谢

1 个答案:

答案 0 :(得分:0)

引用documentation of execute

  

具有与正在执行的SQL语句中的绑定参数一样多的元素的值数组。所有值都被视为 PDO::PARAM_STR

这导致MySQL使用词典比较,并且,正如您所指出的,400&#4; s 4来自2000&2; 2.您可以使用bindValue控制值的界限类型:

# Prepare the query
$stmt = $db->prepare($query);

# Bind values
$stmt->bindValue(':sp1', $_POST['startPoli1'], PDO::PARAM_STR);
$stmt->bindValue(':w1', $_POST['weight1'], PDO::PARAM_INT); # Bind as int!
$stmt->bindValue(':em1', $_POST['eidosmetaf1'], PDO::PARAM_STR);
$stmt->bindValue(':fp1', $_POST['finalPoli1'], PDO::PARAM_STR);
$stmt->bindValue(':dD1', $_POST['depDate1'], PDO::PARAM_STR);

# Execute with the bound parameters
$result = $stmt->execute();