I was given this function question for an interview. I don't think I'm interested in the job and therefore will not submit this, but I am curious how to answer this. Once I start something like this, I can't just quit without knowing the answer.
Questions:
1. Does the function have any errors?
2. What is the purpose of the function?
3. What can be done to improve it?
4. Why is isset() used instead of a simple conditional used above it?
5. What assumptions can you make about the database structure?
function auto_query( $table, $vars ) { $_result = $this->query( "EXPLAIN $_table_name" ); $_fields = array(); // Empty array assigned to variable while( $_row = $_result->fetchRow() ) { array_push( $_fields, $_row['Field'] ); // Push one or more elements onto the end of array } if( $vars[$table . 'id'] ) { $_query = "UPDATE $_table SET "; } else { $_query = "INSERT INTO $_table SET " . $_table . '_date_created = NOW(), '; } $_query_params = array(); // Empty array assigned to variable foreach( $_fields as $_field ) { if( isset( $_vars[$_field] ) ) { $_query_params[] = "$_field = " . $this->dbh->quoteSmart( $_vars[$_field] ); } } $_query .= implode( ',', $_query_params ); // Join array elements with a string if( $_vars[$_table . '_id'] ) { $_query .= " WHERE {$_table}_id = " . $this->dbh->quoteSmart($_vars[$_table . '_id']); } return $_query; }