I am having trouble encoding a mysqli result using json_encode
<?php
$emp_id = $_GET["emp_id"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "overtimedtr";
$jsonData;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM employees where id ='".$emp_id."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
if($row = mysqli_fetch_assoc($result)) {
$empName = $row['name'];
$empPosition = $row['position'];
}
$jsonData = array('empName' => "'".$empName."'",'empPosition' => "'".$empPosition."'");
} else {
//$result["empName"] = '0 results.';
//$result["empPosition"] = '0 results.';
}
$myjson = json_encode($jsonData,JSON_FORCE_OBJECT);
mysqli_close($conn);
echo $myjson;
?>
Error code:
Fatal Error: Uncaught Error: Cannot use object of type mysqli_result as array in line 24.
Stack trace: #0{main} thrown in line 24.
Code starting from line 24:
$empName = $row['name'];
$empPosition = $row['position'];
}
$jsonData = array('empName' => "'".$empName."'",'empPosition' => "'".$empPosition."'");
} else {
//$result["empName"] = '0 results.';
//$result["empPosition"] = '0 results.';
}
$myjson = json_encode($jsonData,JSON_FORCE_OBJECT);
mysqli_close($conn);
echo $myjson;
?>
I wonder if I am missing something obvious here. I am confused by the error because I am thinking that the code below already converts my mysqli_result object type to an associative array?
if($row = mysqli_fetch_assoc($result)) {
$empName = $row['name'];
$empPosition = $row['position'];
}
$jsonData = array('empName' => "'".$empName."'",'empPosition' => "'".$empPosition."'");
I have read similar questions, and could not find any answer that can solve my problem, I am still confused. I am really new to web development, any insights would be so much appreciated. Thank you in advance!