Search code examples
phpmysqlarrayspdobindvalue

Insert An Array To Database using PDO bindValue


I need to insert in one of my tables fields as an array. So I defined a function to convert the input to array like this:

function ConvertToArray($input){
    if( is_array( $input ) ) // for input array type
        return $input ;
    else if( !isset( $input ) || $input == 'undefined' || ($input == "" && $input !==0) || $input == '""' || $input == "''" ){ // for empty input
        $arr = array();
        return $arr ;
    }
    else{  // for string input
        $newarr = array();
        array_push( $newarr, $input );
        return $newarr ;
    }
}

then i want to insert it in database with PDO, but when binding the value i have an error saying:

Array to string conversion error

this is my code:

$usageType = $this -> ConvertToArray($values['UsageType']);
$prepared->bindValue(':UsageType', $usageType); // here is the error

any Idea how to solve my problem? Thanks!


Solution

  • To store array in database, either use serialize() or convert it to json as per your convenient.

    $prepared->bindValue(':UsageType', serialize($usageType));