在准备好的MySQL语句中使用数组中的null值

时间:2017-11-17 14:16:09

标签: php mysql arrays

我一直试图解决这个问题,但是无法找到合适的解决方案。我有一个数据数组,其中一些项目为空。它们在准备好的声明中使用,如下所示:

$query = "insert into stocktake_details 
(created_at, created_by, deleted_at, deleted_by, department_id, edit_flag, full_cost, id, is_damaged, is_expired, is_synced, location_id, orientation, orientation_order,
            position_number, product_id, product_name, product_size_id, quantity, quantity_units, shelf_number, stocktake_id, store_locations_id, total_packed_items, unit_cost, unit_of_measure, updated_at, updated_by, user_id) 

values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?)";
$rowdata =  array_values((array)($data));

            $statement = $conn->prepare($query);
            $product_id = $data->product_id;
            $statement->execute($rowdata);

但是,在准备好的语句中,null被转换为' null'。我已经看到一些提到绑定参数的建议,但我不确定我应该如何使用它们与一系列项目?

1 个答案:

答案 0 :(得分:-1)

绑定参数实际上不是那么难:

// $statement is the prepared statement reference.
// $parameters is an array of all the parameters and as first entry the query itself in order of ? (for mysqli)
// ie. ('select 1...', '1', '1') etc.

$this->DetermineParameterTypes($parameters);
for($key = 1; $key < count($parameters); $key++)
    $parameters[$key] = &$parameters[$key];

// Bind parameters
call_user_func_array(array($statement, "bind_param"), $parameters);

    /**
     * Determine the types of the prepared statement parameters
     *
     * @param array by ref $parameters Parameters
     *
     */
    private function DetermineParameterTypes(&$parameters)
    {
        // Remove first argument this is the $query object
        array_shift($parameters);

        // Determine the parameter types
        $types = '';
        foreach($parameters as $param)
        {
            if((is_int($param) || is_bool($param)) && strpos($param, '.') === false)
                $types .= 'i';              //integer
            elseif (is_float($param) || is_double($param))
                $types .= 'd';              //double
            elseif (is_string($param))
                $types .= 's';              //string
            elseif (is_array($param))
                $types .= 'b';              //blob and unknown
            elseif (is_null($param))
                $types .= 's';              //set null to string type
            else
                $types .= '?';
        }
        array_unshift($parameters, $types);
    }