db/lib.php
/* -----
 * Add an entry to a given collection
 ----- */
Add an entry to a given collection
Add an entry to a given collection
function addEntry ( $connection, $collection, $entry ) {
	try {
		$statement = $connection->prepare( 'DESCRIBE ' . $collection );
		$statement->execute();
		$collectionFields = $statement->fetchAll();
	}
	catch ( PDOException $e ) {
		echo $e->getMessage();
		return FALSE;
	}
	$concernedCollectionFields = array_filter( $collectionFields, function ( $field ) {
		return strpos( $field[ 'Extra' ], 'auto_increment' ) === FALSE;
	} );
	$validCollectionFieldNames = array_map( function ( $field ) {
		return preg_replace( '/\W/', '_', $field[ 'Field' ] );
	}, $concernedCollectionFields );
	$collectionFieldNames = array_map( function ( $field ) {
		return "`${field[ 'Field' ]}`";
	}, $concernedCollectionFields );
	$sql = sprintf(
		'INSERT INTO %s (%s) VALUES (%s)',
		$collection,
		implode( ', ', $collectionFieldNames ),
		':' . implode( ', :', $validCollectionFieldNames )
	);
	$data = array_combine( $validCollectionFieldNames, $entry );
	try {
		$connection->prepare( $sql )->execute( $data );
	}
	catch ( PDOException $e ) {
		return FALSE;
	}
	return TRUE;
}
function addEntry ( $ connection , $ collection , $ entry ) { try { $ statement = $ connection -> prepare ( 'DESCRIBE ' . $ collection ) ; $ statement -> execute ( ) ; $ collectionFields = $ statement -> fetchAll ( ) ; } catch ( PDOException $ e ) { echo $ e -> getMessage ( ) ; return FALSE ; } $ concernedCollectionFields = array_filter ( $ collectionFields , function ( $ field ) { return strpos ( $ field [ 'Extra' ] , 'auto_increment' ) === FALSE ; } ) ; $ validCollectionFieldNames = array_map ( function ( $ field ) { return preg_replace ( '/\W/' , '_' , $ field [ 'Field' ] ) ; } , $ concernedCollectionFields ) ; $ collectionFieldNames = array_map ( function ( $ field ) { return " ` $ { field [ 'Field' ] } ` " ; } , $ concernedCollectionFields ) ; $ sql = sprintf ( 'INSERT INTO %s (%s) VALUES (%s)' , $ collection , implode ( ', ' , $ collectionFieldNames ) , ':' . implode ( ', :' , $ validCollectionFieldNames ) ) ; $ data = array_combine ( $ validCollectionFieldNames , $ entry ) ; try { $ connection -> prepare ( $ sql ) -> execute ( $ data ) ; } catch ( PDOException $ e ) { return FALSE ; } return TRUE ; }
Add an entry to a given collection
Add an entry to a given collection
// Get the names of the fields of the collection // Insert the values into the collection // echo $e->getMessage();