4

I have a situation where i have to programmatically do database inserts. I have multiple tables but the order of information of those tables are similar , i.e, in each table, the first coulmn in id, and second is a foregin key, and third is a name, and fourth is a blob and fifth is a text.

I searched php doc and found that I can use $objectName[index] to access the database property. I am getting error

Cannot use object of type stdClass as array in C:\....php on line .. .

The erroneous line is indicated on the code

private function uploadTemp($databaseObject, $table_name){
    $this->load->database();
    //get file_contents too;
    $file_id = $databaseObject[3]; // < Here's where the error appeared
    $this->db->from('tbl_file')->where('file_id',$file_id); 
    $q = $this->db->get();
    $data = $q->row();
    $query = "INSERT INTO $table_name VALUES(NULL, '".$databaseObject[2]."','".$data->filecontent."');";
    $this->db->query($query);
}

I am using CodeIgniter as a framework.

2
  • Isn't it the line before the marked one, i.e. $file_id = $databaseObject[3]; that triggers the error? Commented Jun 26, 2013 at 7:32
  • @VolkerK The second line trigged that! That made be surprised! Commented Jun 26, 2013 at 7:33

2 Answers 2

5

Try casting to array:

$file_id = (array) $databaseObject[3];

As STDClass is just a dummy container with public dynamic variables and no methods, there should be no problems in casting it to array and backwards as well.

However in some situations numbers are used to represent a variable name.

Example:

$array ; //Is some array created by engines / database handlers.

$obj = (object) $array ;

echo $obj->0 ; //Hell it will not work.
echo $obj[0] ; //The same problem.

echo $obj->{'0'} ; //PERFECT
Sign up to request clarification or add additional context in comments.

3 Comments

What if you try: $file_id = $databaseObject->{'3'}; ?
Actually my database object had different identifiers depending upon cases, but had the same kind of data in the third position! And I was trying to get the third data. I guess the method is same!
IMO it is a really wrong stuff that CodeIgniter encases data into objects. Objects must contain properties with real names. Arrays must contain sets of data and be number-indexed usually.
1

try this function get_object_vars()

or create function to convert to array

function array_to_object($array)//from CodeIgniter forum
 {
  return (is_array($array)) ? (object) array_map(__FUNCTION__, $array) : $array;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.