DatabaseUtil::create_primary_key()publicWC 1.0

Create a primary key for a table, only if the table doesn't have a primary key already.

Method of the class: DatabaseUtil{}

No Hooks.


true|false. True if the key has been created, false if the table already had a primary key.


$DatabaseUtil = new DatabaseUtil();
$DatabaseUtil->create_primary_key( $table_name, $columns );
$table_name(string) (required)
Table name.
$columns(array) (required)
An array with the index column names.

DatabaseUtil::create_primary_key() code WC 8.9.0

public function create_primary_key( string $table_name, array $columns ) {
	global $wpdb;

	if ( ! empty( $this->get_index_columns( $table_name ) ) ) {
		return false;

	// phpcs:ignore WordPress.DB.PreparedSQL
	$wpdb->query( "ALTER TABLE $table_name ADD PRIMARY KEY(`" . join( '`,`', $columns ) . '`)' );
	return true;