MySql查询无法使用变量奇怪的bug

时间:2016-03-13 18:58:16

标签: php sql

我有一个用户ID列表,我的目标是使用id

获取每个用户的名称

sql变量打印:SELECT name FROM users WHERE unique_id =' 56d4814fb37cf3.17691034'

如果我复制粘贴查询,则返回名称并与其他ID一起使用,但我不希望函数总是返回相同的名称,我想将变量$ userID添加到我的查询中返回名称

但这仅在我硬编码时才有效



public function returnNameByID($userID){
 //User ID: 56d4814fb37cf3.17691034 
	
    $sql =  "SELECT name FROM users WHERE unique_id = '$userID'";
	
  echo $sql; // Prints SELECT name FROM users WHERE unique_id = '56d4814fb37cf3.17691034 '
	
//Doesn't work $name returns Null
//  $stmt = $this->conn->prepare("SELECT name FROM users WHERE unique_id = '$userID'"); 

//Doesn't work $name returns Null
	$stmt = $this->conn->prepare($sql); 

// Works $name returns name of the user
   $stmt = $this->conn->prepare(" SELECT name FROM users WHERE unique_id = '56d4814fb37cf3.17691034 ' "); 

    $stmt->execute();
	
    $result = $stmt->get_result()->fetch_assoc();
	
    $name = $result["name"];

    return $name;




修改



require_once 'db_functons.php';
$db = new db_functions();

$userID = $_GET['userID'];
$mArray =  array();

$mArray = $db->getFriendsList($userID);
//Printing the array Prints the correct id's

$name = $db->returnNameByID($mArray[0]);
echo $name;




1 个答案:

答案 0 :(得分:2)

似乎你的代码周围有一些空间尝试使用trim

$sql =  "SELECT name FROM users WHERE trim(unique_id) = '" . trim($userID) . "';";