Mysqli_result class object cannot be converted to string just by creating a query
I have asked many questions, I am new to mysqli.
This is my code:
function user_data($user_id, $con) {
$data = array();
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 2) {
unset($func_get_args[0]);
unset($func_get_args[1]);
$fields = '`' . implode('`, `', (array)$func_get_args) . '`';
$result = mysqli_query($con, "SELECT $fields FROM `users` WHERE `user_id` = $user_id");
while ($row = mysqli_fetch_assoc($result)) {
return $row[$fields];
}
}
}
This is mistake
Spoofed fatal error: class object mysqli_result cannot be converted to string in C: \ Users \ DCV_Diego \ Dropbox \ vment \ htdocs \ LOL \ all \ functions \ users.php on line 15
This is line 15:
$result = mysqli_query($con, "SELECT $fields FROM `users` WHERE `user_id` = $user_id");`
I don't understand why this error appears, I am not using mysqli_query
as a string, I am using a while loop to return the string data. At least maybe the error should be on the line return
...
Edit:
This is my new code
function user_data($user_id, $con, $fields) {
$data = array();
$fields = '`' . implode('`, `', $fields) . '`';
$result = mysqli_query($con, "SELECT $fields FROM `users` WHERE `user_id` = $user_id");
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
return $data;
}
It still doesn't work !!!!
Here is my line calling the function
$user_data = user_data($session_user_id, $con, $fields);
(BTW I'm trying to indent and it just doesn't work -, -)
source to share
There are a lot of problems here:
The first assumption is that $con
is a mysqli connection, so you cannot use it and assign it as fields and use them for implode()
.
Second, after that you need to add another parameter that contains the actual fields (you can use an array for this).
Don't use return
inside a loop, collect results first, then finally use return at the end.
/**
Legend:
$con is for the mysqli connection
$user_id = is going to be used in WHERE clause
$fields is the columns
**/
function user_data($con, $user_id, $fields) {
$data = array();
$fields = implode(', ', $fields);
$result = mysqli_query($con, "SELECT $fields FROM users WHERE user_id= $user_id");
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
return $data;
}
$con = new mysqli('localhost', 'username', 'password', 'database_name');
$fields = array('col1', 'col2', 'col3');
$user_id = 1;
$data = user_data($con, $user_id, $fields);
source to share