带有WHERE子句的Mysql SELECT无法使用变量

时间:2015-03-13 01:52:26

标签: php mysql variables select where

我正把头发拉出来。我有两个SELECT语句基本上是相同的主体。第一个是工作,第二个不能使用WHERE子句。我需要一些新鲜的眼睛和建议。我一直在每个论坛上阅读每一篇文章并试过很多“解决方案”都无济于事。希望有人会看到我错过的东西。

$oID = zen_db_prepare_input($_GET['oID']);

  // Color coding for invoice -Start queries---

  $query = "SELECT * FROM cart1_orders WHERE orders_id = $oID";
  $result = $db->Execute($query); 
  $shiploc = $result->fields['shipping_method'];
  if ($result->RecordCount() > 0) { 
  echo 'Test Query: = ' . $result->fields['shipping_method']; 
  } else { 
  echo 'Sorry, no record found for product number ' ; 
  }  

  $sql = "SELECT * FROM cart1_store_locations  WHERE pickup_name= $shiploc";
  $results = $db->Execute($sql); 
  $newcolorblock = $results->fields['color_code'];
  if ($results->RecordCount() > 0) { 
  echo 'Color Query: = ' . $results->fields['color_code'];
  echo 'Location: = '. $results->fields['pickup_name']; 
  } else { 
  echo 'Sorry, no record found for Color Code ' ; 
  }  

提前感谢您的帮助和建议,希望您能够看到我无法做到的事情。

首先查询结果:测试查询:=存储取件(Mooresville - Gold's Gym) 第二个查询结果:警告:发生错误,请刷新页面并重试。

如果删除WHERE子句,则返回值但不返回正确的值。我需要WHERE语句才能获取正确的信息。

ANSWER 由bloodyKnuckles友情提供:)

$sql= "SELECT * FROM cart1_store_locations WHERE pickup_name= $shiploc";

更改为:(需要转义为表格数据中的's')

$shiploc_escaped = mysql_escape_string($shiploc);
$sql = "SELECT * FROM cart1_store_locations  WHERE pickup_name=       '".$shiploc_escaped."'";

我之前没有使用过这个论坛。爱它!!!谢谢大家!

2 个答案:

答案 0 :(得分:0)

您的$shiploc可能是null。在第二次查询之前,请写下var_dump($shiploc);并告诉我们你得到了什么。

修改

$oID = zen_db_prepare_input($_GET['oID']);

  // Color coding for invoice -Start queries---

  $query = "SELECT * FROM cart1_orders WHERE orders_id = $oID";
  $result = $db->Execute($query); 
  $shiploc = $result->fields['shipping_method'];
  if ($result->RecordCount() > 0) { 
  echo 'Test Query: = ' . $result->fields['shipping_method']; 
  } else { 
  echo 'Sorry, no record found for product number ' ; 
  }  

  $sql = "SELECT * FROM cart1_store_locations  WHERE pickup_name= '".$shiploc."'";
  $results = $db->Execute($sql); 
  $newcolorblock = $results->fields['color_code'];
  if ($results->RecordCount() > 0) { 
  echo 'Color Query: = ' . $results->fields['color_code'];
  echo 'Location: = '. $results->fields['pickup_name']; 
  } else { 
  echo 'Sorry, no record found for Color Code ' ; 
  }  

答案 1 :(得分:0)

由于您的字符串中包含单引号:

  

商店皮卡(Mooresville - Gold's Gym)

...你需要转义变量$shiploc

$shiploc_escaped = addslashes($shiploc);
$sql = "SELECT * FROM cart1_store_locations  WHERE pickup_name= '".$shiploc_escaped."'";

阅读Zen Cart Escaping Content,看来这是一个选项:

$sql = "SELECT * FROM cart1_store_locations  WHERE pickup_name= '".$db->prepare_input($shiploc)."'";

......而且,更好的是,这个:

$sql = "SELECT * FROM cart1_store_locations WHERE pickup_name= :pickup_name:";
$sql = $db->bindVars($sql, ':pickup_name:', $shiploc, 'string');