Oliver norton Oliver norton - 3 months ago 116
MySQL Question

Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\PokemonFight\pokemon.php on line 14

I know that this question has been asked many times before.

However, I'm unable to find a scenario that helps me solve the issue that I'm having.

Here is my code:

<?php
session_start();
$db = mysqli_connect("localhost", "root", "password", "authentication");

if (isset($_POST['login_btn'])) {

$username = mysqli_real_escape_string($db,$_POST['username']);
$password = mysqli_real_escape_string($db,$_POST['password']);

$password = md5($password);
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($db, $sql);

$idsql = "SELECT id FROM users WHERE username='$username'";
$userid = mysqli_query($db, $idsql);



if (mysqli_num_rows($result) == 1) {
$_SESSION['message'] = "You are now logged in";
$_SESSION['username'] = $username;
$_SESSION['userid'] = $userid;
header("location: home.php");
}else{
$_SESSION['message'] = "Username/password combination incorrect";
}
}
?>


The
_SESSION
variable for
username
works really well with no problems. However when I go to echo the
_SESSION
for
userid
I receive an error. I've attempted many different solutions but I just can't seem to find the one that will fit this problem.

This is the error code:


"Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\PokemonFight\pokemon.php on line 14"

The line 14 of code that it is referring to also is:




I'm at a total loss as to how to get it to echo the correct user id.

Answer

It looks like you're trying to convert a mysqli_query object into a string.

$idsql = "SELECT id FROM users WHERE username='$username'";
$userid = mysqli_query($db, $idsql);

You need to fetch the results and then pull the id field from the results. Then use that to attach to the $_SESSION variable.

e.g:

$idsql = "SELECT id FROM users WHERE username='$username'";
$userid = mysqli_query($db, $idsql);
$userid = mysqli_fetch_row($userid);
$userid = $userid[0];

And then populate that into the $_SESSION variable. Otherwise, when you try to output the result of $_SESSION['userid'] using echo it fails because it's attempting to do an object to string conversion.

You could also try to print_r($_SESSION['userid']); to see this in effect.