Dynamically bind mysqli_stmt parameters and then bind result (PHP)

后端 未结 4 1839
忘了有多久
忘了有多久 2020-12-03 12:27

I\'m trying to dynamically bind mysql_stmt parameters and get the result in an associative array. I\'ve found this post here on stackoverflow where Amber posted an answer wi

4条回答
  •  天命终不由人
    2020-12-03 13:14

    After using the answer above I have figured out that there was some cleanup needed for myself, particularly the 'fieldNames[]' portion. The code below is in procedural style. I hope it will come of use to someone.

    I cut the code from a class I made that can dynamically query data. There are a few things I removed to make it easier to read. In the class I have I allow the user to define definitions tables and foreign keys so that data entry on the front-end is restricted as well as filter and sort options for said related data. These are all parameters I removed as well as the automated query builder.

    $query = "SELECT `first_name`,`last_name` FROM `users` WHERE `country` =? AND `state`=?";
    $params = array('Australia','Victoria');
    
    ////////////// GENERATE PARAMETER TYPES IF ANY //////////////
    // This will loop through parameters, and generate types. ex: 'ss'
    $types = '';
    $params_size = sizeof($params);
    if($params_size > 0)
    {
        foreach($params as $param)
        {
            if(is_int($param))
            {
                $types .= 'i';              //integer
            }else if(is_float($param))
            {
                $types .= 'd';              //double
            }else if(is_string($param))
            {
                $types .= 's';              //string
            }else
            {
                $types .= 'b';              //blob and unknown
            }
        }
        array_unshift($params, $types);
    }
    ////////////////////////////////////////////////////////////
    
    
    // This is the tricky part to dynamically create an array of
    // variables to use to bind the results
    
    //below from http://php.net/manual/en/mysqli-result.fetch-field.php
    /*
    name        The name of the column
    orgname     Original column name if an alias was specified
    table       The name of the table this field belongs to (if not calculated)
    orgtable    Original table name if an alias was specified
    def         Reserved for default value, currently always ""
    db          Database (since PHP 5.3.6)
    catalog     The catalog name, always "def" (since PHP 5.3.6)
    max_length  The maximum width of the field for the result set.
    length      The width of the field, as specified in the table definition.
    charsetnr   The character set number for the field.
    flags       An integer representing the bit-flags for the field.
    type        The data type used for this field
    decimals    The number of decimals used (for integer fields)
    */
    
    /// FIELD TYPE REFERENCE ///
    /*
    numerics
    -------------
    BIT: 16
    TINYINT: 1
    BOOL: 1
    SMALLINT: 2
    MEDIUMINT: 9
    INTEGER: 3
    BIGINT: 8
    SERIAL: 8
    FLOAT: 4
    DOUBLE: 5
    DECIMAL: 246
    NUMERIC: 246
    FIXED: 246
    
    dates
    ------------
    DATE: 10
    DATETIME: 12
    TIMESTAMP: 7
    TIME: 11
    YEAR: 13
    
    strings & binary
    ------------
    CHAR: 254
    VARCHAR: 253
    ENUM: 254
    SET: 254
    BINARY: 254
    VARBINARY: 253
    TINYBLOB: 252
    BLOB: 252
    MEDIUMBLOB: 252
    TINYTEXT: 252
    TEXT: 252
    MEDIUMTEXT: 252
    LONGTEXT: 252
    */
    
    if($stmt = mysqli_prepare($db_link, $query))
    {
        // BIND PARAMETERS IF ANY //
        if($params_size > 0)
        {
            call_user_func_array(array($stmt, 'bind_param'), makeValuesReferenced($params));
        }
    
        mysqli_stmt_execute($stmt);
    
        $meta = mysqli_stmt_result_metadata($stmt);
    
    
        $field_names = array();
        $field_length = array();
        $field_type = array();
        $output_data = array();
    
        /// THIS GET THE NAMES OF THE FIELDS AND ASSIGNS NEW VARIABLES USING THE FIELD NAME. THESE VARIABLES ARE THEN SET TO NULL ///
        $count = 0;
        while($field = mysqli_fetch_field($meta))
        {
            $field_names[$count] = $field->name;// field names
            $var = $field->name;
            $$var = null;
            $field_names_variables[$var] = &$$var;// fields variables using the field name
            $field_length[$var] = $field->length;// field length as defined in table
            $field_type[$var] = $field->type;// field data type as defined in table (numeric return)
            $count++;
        }
        setFieldLengthInfo($field_length);
        setFieldTypesInfo($field_type);
    
        $field_names_variables_size = sizeof($field_names_variables);
        call_user_func_array(array($stmt, 'bind_result'), $field_names_variables);
    
        $count = 0;
        while(mysqli_stmt_fetch($stmt))
        {
            for($l = 0; $l < $field_names_variables_size; $l++)
            {
                $output_data[$count][$field_names[$l]] = $field_names_variables[$field_names[$l]];/// THIS SETS ALL OF THE FINAL DATA USING THE DYNAMICALLY CREATED VARIABLES ABOVE
            }
            $count++;
        }
        mysqli_stmt_close($stmt);
    
    
        echo "
    ";
        print_r($output_data);
        echo "
    "; } function makeValuesReferenced($arr) { $refs = array(); foreach($arr as $key => $value) $refs[$key] = &$arr[$key]; return $refs; }

提交回复
热议问题