3

我有一个非常基本的选择语句导致列未知错误。当我尝试在变量中使用字符而不是数字时,就会出现查询问题。想知道它是否与排序规则有关。

这是我到目前为止所拥有的:

$titleno=$_REQUEST['title_no'];
$titleno=mysql_real_escape_string($titleno);
$titleno = utf8_decode($titleno); //tried without this before but didn't work
$query="SELECT * FROM `Titles` WHERE `title-no` = '".$titleno."'"; 
//tried various versions of this query - left it as single quotes as that seems to be the correct way. This only fails when a character is entered. Numbers work fine.  

echo "query - <br> $query <br>";    
$get_title_result=mysql_query($query) or die(mysql_error());
//here I get the unknown column name error - MySQL treats the titleno as the column name 

回声输出:

SELECT * FROM `Titles` WHERE `title-no` = '1234566d' 
Unknown column '1234566d' in 'where clause'

如果我没有在 title-no 中使用“d”,它可以正常工作....此外,我尝试了一个没有连字符的不同列名,但仍然得到相同的行为。DB 将 title-no 的排序规则定义为 latin1_swedish_ci。(当我将查询粘贴到 mysqladmin 时不会出现此问题)

这是表定义:

CREATE TABLE `Titles` (  
 `id` int(11) NOT NULL auto_increment,  
 `title-no` varchar(15) NOT NULL,  
  UNIQUE KEY `title-no` (`title-no`),  
  KEY `id` (`id`)  
  ) ENGINE=MyISAM  
  AUTO_INCREMENT=9090949 DEFAULT CHARSET=latin1 AUTO_INCREMENT=9090949 ;

已解决:问题不在于此查询。这是随后的查询。我很困惑,因为我只是在回应这个查询。我的错。谢谢大家的支持!:)

4

2 回答 2

0

尝试:

$query = "SELECT * FROM Titles WHERE `Titles`.`title-no` = '" . $titleno . "'"; 
于 2012-07-14T01:43:25.767 回答
0

这是对基于语句的查询的快速转换(使用 MySQLi,根据需要调整您的代码或此示例)。假设基础准备好的语句引擎知道您不能在准备好的语句中指定带有占位符的列名,因此它应该正确传递它(希望:-)

$titleno=$_REQUEST['title_no'];
$statement=mysqli_prepare($your_mysqli_link, "SELECT `id` FROM `Titles` WHERE `title-no` = ?"); 
mysqli_stmt_bind_param($statement, 's', $titleno);
mysqli_stmt_execute($statement);
mysqli_stmt_bind_result($statement, $found_id);
mysqli_stmt_fetch($statement);
echo "found id: $found_id";
于 2012-07-14T02:31:25.127 回答