code here :
$mysqli = new mysqli($servername, $username, $password, $database); $userId1 = $_SESSION['user']['userId']; $searchQuery = "SELECT ClassName FROM classrooms WHERE userid = '{$userId1}'"; echo "abc"; if ($mysqli->query($searchQuery) === TRUE) { echo "epic"; while($row = $searchQuery->fetch_object()) { echo $row['ClassName']; } }
I am trying to echo all instances where the userId in the classrooms table is equal to the session userId. HELP.
this is the table that we are using to track the users classrooms I’m using mysqli.
ClassName userid yoink 25 lol 25 haha 6 yoinks 25 yeet 25 yeet1 25
Turns out, my post is mostly code. So let me give some background details. I’m trying to make a table that will disply the classroom name depending on the userID. So user 25 will have classrooms yoink,lol,yoinks,yeet, and yeet1. But the if statement (our query) doesn’t actually do anything.
Many thanks
Advertisement
Answer
$searchQuery
is a string!!! And not a result handle which would have been returned from $mysqli->query()
but you did not capture it.
So change the code to
$mysqli = new mysqli($servername, $username, $password, $database); $userId1 = $_SESSION['user']['userId']; $searchQuery = "SELECT ClassName FROM classrooms WHERE userid = '$userId1'"; echo "abc"; if ($result = $mysqli->query($searchQuery) === TRUE) { echo "epic"; while($row = $result->fetch_object()) { //echo $row['ClassName']; // you fetch an OBJECT so address it as an object echo $row->ClassName; } }
However – Big Warning
Your script is open to SQL Injection Attack. Even if you are escaping inputs, its not safe! You should consider using prepared parameterized statements in either the
MYSQLI_
orPDO
API’s instead of concatenated values
$mysqli = new mysqli($servername, $username, $password, $database); $userId1 = $_SESSION['user']['userId']; $sql = "SELECT ClassName FROM classrooms WHERE userid = ?"; $stmt = $mysqli->prepare($sql); $stmt->bind_param('s', $userId1); $stmt->execute(); $result = $stmt->get_result(); while($row = $result->fetch_object()) { echo $row->ClassName; }