简体   繁体   中英

MySql query not working with variables weird bug

I have a list of users ids and my goal is to get the name of each user using the id

the sql variable prints: SELECT name FROM users WHERE unique_id = '56d4814fb37cf3.17691034 '

If i copy paste the query the name is returned and works as well with other ids, but i don't want the function to allways return the same name, i want to add the variable $userID to my query and return the name

But this only works when i hardcode de id

 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; 

EDIT

 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; 

似乎您的代码周围有一些空间,请尝试使用修剪

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM