Dynamically bind params in $bind_param(); Mysqli

后端 未结 2 1624
悲哀的现实
悲哀的现实 2021-01-23 23:42

I have DB class which is dealing all queries will be made to database I have mysqli prepare working fine. bind_param is also working fine but the problem is I want to define va

2条回答
  •  星月不相逢
    2021-01-23 23:44

    Here is an example that could help ( prepare() function is a class method ).

    function prepare( $query, $bind = array() )
    {   
        if ( !$stmt = $this->mysqli->prepare( $query ) ) 
            throw new Exception( 'Query failed: ' . $query . PHP_EOL . $this->mysqli->error );  
    
        // if $bind is not an empty array shift the type element off the beginning and call stmt->bind_param() with variables to bind passed as reference
        if ( $type = array_shift( $bind ) )
            call_user_func_array( 
                array( $stmt, 'bind_param' ), 
                array_merge( array( $type ), array_map( function( &$item ) { return $item; }, $bind ) ) 
            );
    
        if ( !$stmt->execute() ) 
            throw new Exception( 'Execute failed: ' . PHP_EOL . $stmt->error );
    
        // choose what to return here ( 'affected_rows', 'insert_id', 'mysqli_result', 'stmt', 'array' ) 
    
    }
    

    Example of usage:

    $db->prepare( "SELECT * FROM user WHERE user_name = ? OR user_email = ?", [ 'ss', $user_name, $user_name ] );
    

提交回复
热议问题