Jump to content

object of class mysqli_result could not be converted to string


mattchamp97

Recommended Posts

The following is an extract of PHP code I have interacting with a MySQL database and I keep getting the "object of class mysqli_result could not be converted to string" error on the line of code inside my loop. This is my code.

 

#This is just storing a single integer, a moduleID

$sqlmodID = mysqli_query($con,"select moduleID from module_details WHERE moduleName = '$moduleName' AND lecturerID = '$lecturerID'");
            

#This is a query to get relevant idNumbers            

$sqlstudent = "select idNum from user_info WHERE courseCode = '$courseCode'";

 

#Running the previous statement

$result = mysqli_query($con, $sqlstudent);

 

#Storing the statements results in an array 

$row = mysqli_fetch_array($result);

 

#I'm not sure if this line is necessary but it converts the array values into a string (I'm storing the ID's as strings as they contain numbers and letters)

$studentArray = array_map('strval', $row);

 

#The error flashes on my condition of this loop. I'm trying to take each element of my array, and enter it to my table, assigning each variable the same ModuleID.

for($i=0; $i < count($studentArray); $i++){
                mysqli_query($con,"insert into student_classlist VALUES ('$sqlmodID', '$studentArray')");
 }

 

Any help would be much appreciated. I hope I've explained my code sufficiently.

Link to comment
Share on other sites

20 minutes ago, ginerjm said:

Do we have a line number that points to the one causing the error? 

Hi,

Yes there's a line number identifying that the error I'm getting is with the condition inside the loop. The whole error message is as follows:

"Recoverable fatal error: Object of class mysqli_result could not be converted to string in /storage/ssd5/641/12544641/public_html/newmodule.php on line 54"

Link to comment
Share on other sites

That makes sense but not for that error message.  YOu are in a loop with an index but you are not USING the index.  How about $studentarray[$i] ?

AND - You are referencing the result of your first query which is an array as well.  How about doing a fetch on it to get the actual value you want to use?

Edited by ginerjm
Link to comment
Share on other sites

18 minutes ago, ginerjm said:

That makes sense but not for that error message.  YOu are in a loop with an index but you are not USING the index.  How about $studentarray[$i] ?

AND - You are referencing the result of your first query which is an array as well.  How about doing a fetch on it to get the actual value you want to use?

Which query do you mean? The one to set the value of $sqlModID? This is only storing a single integer value.

If you meant the result of mysqli_query($con, $sqlstudent);  , I'm using the line after this to store it in an array named row, which I then converted the contents of to string values.

I don't understand how to use fetch on this as I'm only new to PHP, would you be able to show me some sort of example? 

Thanks very much for your help with this.

Link to comment
Share on other sites

If you read the manual you would see that the result of any query is a resource, not an array.  You need to do a fetch or some other operation to extract any values from this query result resource.

As for the array map that simply processes an array and produces an array result.  Read the manual again.  The manual is your friend.  Very interesting reading for a noob.

If you want to post this block of code we can see the (slightly) bigger picture and add some lines perhaps.

Edited by ginerjm
Link to comment
Share on other sites

2 minutes ago, ginerjm said:

If you read the manual you would see that the result of any query is a resource, not an array.  You need to do a fetch or some other operation to extract any values from this query result resource.

As for the array map that simply processes an array and produces an array result.  Read the manual again.  The manual is your friend.  Very interesting reading for a noob.

If you want to post this block of code we can see the (slightly) bigger picture and add some lines perhaps.

<?php

    require "init.php";
    
	$lecturerID = $_POST["lecturerID"];
	$moduleName = $_POST["moduleName"];
	$courseCode = $_POST["courseCode"];
	$moduleID = NULL;
	
	$sql = "select * from user_info where idNum = '$lecturerID' AND accountType = 'Lecturer'";
	
	$sqlresp = mysqli_query($con,$sql);
	$rowcount = mysqli_num_rows($sqlresp);
	
	if($rowcount<1)
	{
		$response = array();
		$code = "module_creation_error";
		$message = "Please enter a valid Lecturer ID.";
		
		//Push variables $code and $message into an array
		array_push($response,array("code"=>$code,"message"=>$message));
		
		//Put array into a JSON object to push to the app
		echo json_encode(array("server_response"=>$response));
	}
	else
	{
		//Inserting new module details into module table
		$sqlinsert = "insert into module_details(lecturerID,moduleName,classListCourseCode) VALUES ('$lecturerID', '$moduleName', '$courseCode')";
		
		$insertresult = mysqli_query($con,$sqlinsert);
		
		if($insertresult)
		{
		    $response = array();
			$code = "module_created";
			$message = "Your new module was created successfully.";
			
			$sqlmodID = mysqli_query($con,"select moduleID from module_details WHERE moduleName = '$moduleName' AND lecturerID = '$lecturerID'");
			
			$sqlstudent = "select idNum from user_info WHERE courseCode = '$courseCode'";
			
			$result = mysqli_query($con, $sqlstudent);
			
			$row = mysqli_fetch_array($result, MYSQLI_NUM);
			
			$studentArray = array_map('strval', $row);
		
			for($i=0; $i < count($studentArray); $i++)
			{
				mysqli_query($con,"insert into student_classlist VALUES ('$sqlmodID', '$studentArray[$i]')");
			}
			
			//Push variables $code and $message into an array
			array_push($response,array("code"=>$code,"message"=>$message));
			
			//Put array into a JSON object to push to the app
			echo json_encode(array("server_response"=>$response));
		}
		else
		{
			$response = array();
			$code = "module_insert_error";
			$message = "Server Error. Try again";
			
			//Push variables $code and $message into an array
			array_push($response,array("code"=>$code,"message"=>$message));
			
			//Put array into a JSON object to push to the app
			echo json_encode(array("server_response"=>$response));
		}
	}	
	
	mysqli_close($con);
	
?>

That's my whole file there. Basically once a module is created, I want to populate a different table, student_classlist based on the values passed to this script.

I've read through the manual but came here as I found some parts of it confusing.

I have used mysqli_fetch_array on the resource returned by the query to get my array if this is what you mean. Or are you saying I need to do a fetch on $result and $sqlmodID ?

Link to comment
Share on other sites

Working with just the code that you seemed to have difficuly with:

if($insertresult)
{
    $response = array();
    $code = "module_created";
    $message = "Your new module was created successfully.";
    //  Get a module id
    $q = "select moduleID from module_details 
            WHERE moduleName = '$moduleName' AND 
                    lecturerID = '$lecturerID'";
    if (!$sqlmodID = mysqli_query($con, $q))
    {
        echo "Module Id could not be researched";
        exit();
    }
    // Get id from query results
    $row = mysqli_fetch_assoc($con, $sqlmodID);
    $modid = $row['moduleID'];
    //  query for students taking this course
    $sqlstudent = "select idNum from user_info WHERE courseCode = '$courseCode'";
    $result = mysqli_query($con, $sqlstudent);
    //  Q. Are you seeking all students or is there only one?
    //  IF more than one you should have a loop here instead of a fetch
    $row = mysqli_fetch_assoc($con, $result);
    $q = "insert into student_classlist VALUES ('$modid', '" . $row['idNum'] . "'";
    if (!mysqli_query($con, $q))
    {
        $echo "Could not insert new record in classlist for $modid - " . $row['idNum'];
        exit();
    }
...
...
...

Note - do error checking when you write code

Also I highly suggest that you not adopt JS naming conventions when using php.  It will bite you in the A..  eventually for no good reason.  Vars can be all lowercase so that you don't have to search all over for where you misplaced a capital letter later on.

Your student query seems to be looking for multiple people yet your code really treated it as if it was one row when you did the lone fetch prior to the if statement.  As that seemed to be the focus I dropped your if loop.  If you are looking for multiple students I suggest a loop using the fetch something like:

	while ($row = mysqli_fetch_assoc($result)
	{
	    process one row
	}
	
Edited by ginerjm
Link to comment
Share on other sites

Hi, thanks very much for your help. I've just tried to run the following code.

if($insertresult)
		{
		    $response = array();
			$code = "module_created";
			$message = "Your new module was created successfully.";
			
			$q = "select moduleID from module_details WHERE moduleName = '$moduleName' AND lecturerID = '$lecturerID'";
			
			if (!$sqlmodID = mysqli_query($con, $q))
            {
                echo "Module Id could not be researched";
                exit();
            }
            
			$row = mysqli_fetch_assoc($sqlmodID);
			$modid = $row['moduleID'];
			
			$sqlstudent = "select idNum from user_info WHERE courseCode = '$courseCode'";			
			$result = mysqli_query($con, $sqlstudent);
			
			while($row = mysqli_fetch_assoc($result))
			{
				mysqli_query($con,"insert into student_classlist VALUES ('$modid', '" . $row['idNum'] . "'");
			}
			
			//Push variables $code and $message into an array
			array_push($response,array("code"=>$code,"message"=>$message));
			
			//Put array into a JSON object to push to the app
			echo json_encode(array("server_response"=>$response));
		}

As you questioned in your previous post, I am seeking all student IDs, not just one.

I tried to implement a loop as you suggested with this while loop where I am processing one row at a time but it does not seem to be giving me my desired results.

Am I processing the rows incorrectly in my while loop or where have I gone wrong?

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.