Automattic\WooCommerce\Blueprint
Util::array_to_insert_sql
Convert an array to an insert SQL query.
Method of the class: Util{}
No Hooks.
Returns
false|String.
Usage
$result = Util::array_to_insert_sql( $row, $table, $type );
- $row(array) (required)
- Array row with key and value.
- $table(string) (required)
- Name of the table.
- $type(string)
- One of insert, insert ignore, replace into.
Default:'insert ignore'
Util::array_to_insert_sql() Util::array to insert sql code WC 10.8.1
public static function array_to_insert_sql( $row, $table, $type = 'insert ignore' ) {
if ( empty( $row ) || ! is_array( $row ) ) {
return false; // Return false if input data is empty or not an array.
}
$allowed_types = array( 'insert', 'insert ignore', 'replace into' );
if ( ! in_array( $type, $allowed_types, true ) ) {
return false; // Return false if input type is not valid.
}
// Get column names and values.
$columns = '`' . implode( '`, `', array_keys( $row ) ) . '`';
$escaped_values = array_map( fn( $value ) => "'" . addslashes( $value ) . "'", $row );
$values = implode( ', ', $escaped_values );
// Construct final SQL query.
return "{$type} `$table` ($columns) VALUES ($values);";
}