I don’t use PDO, use mysqli_
but anyway it is an optimization of a generic insertion or update function:
/**
* Insere dados numa tabela.
*
* @param string $table nome da tabela
* @param array $data field=>value
* @param array $format %i,%d,%s,%b (int, double, string, blob)
* @return boolean retorna verdadeiro se inseriu, senão falso.
*
*/
function insert( $table, $data, $format )
{
$conn = connect();
if ( empty( $table ) || empty( $data ) )
{
return false;
}
$data = (array) $data;
$format = (array) $format;
$format = implode( '', $format );
$format = str_replace( '%', '', $format );
list( $fields, $placeholders, $values ) = prep_query( $data );
array_unshift( $values, $format );
$sql_insert = "INSERT INTO {$table} ({$fields}) VALUES ({$placeholders}) ON DUPLICATE KEY UPDATE ";
$first = 1;
foreach ( $data as $field => $item )
{
if( $first != 1 ) $sql_insert.=", ";
$sql_insert.= "$field=VALUES($field)";
$first = 0;
}
$stmt = $conn->prepare( $sql_insert );
call_user_func_array( array($stmt, 'bind_param'), ref_values( $values ) );
$stmt->execute();
if ( $stmt->affected_rows || $stmt->insert_id )
{
return true;
}
return false;
}
/**
* Pepara os campos de dados e respetivos valores.
*
* @param $data
* @return array
*/
function prep_query( $data )
{
$fields = '';
$placeholders = '';
$values = array();
foreach ( $data as $field => $value )
{
$fields .= "{$field},";
$values[] = $value;
$placeholders .= '?,';
}
$fields = substr( $fields, 0, -1 );
$placeholders = substr( $placeholders, 0, -1 );
return array($fields, $placeholders, $values);
}
/**
* Referencia os valores para que estes possam ser alterados.
*
* @param $array
* @return array
*/
function ref_values( $array )
{
$refs = array();
foreach ( $array as $key => $value )
{
$refs[$key] = &$array[$key];
}
return $refs;
}
Here is an example of use:
/*********************** exemplo de inserção de um user ************************
$data =
array(
'id' => NULL,
'name' => "JorgeB.",
'password' => "1234"
);
$format = array('i','s','s');
$table = "users";
insert($table, $data, $format);
*******************************************************************************/
Miguel se a query selection is simple so it works perfectly. But what if you need a
INNER JOIN
for example?– Jorge B.
I always find it difficult to do a generalist selection function. I can already insert and update easily. Although they are a little more complex than these, since they can receive a array column and data.
– Jorge B.
In that case, the
INNER JOIN
, would do apart. You can give an example of these more complex functions sff?– Miguel
Miguel has my example, but with
myslqi_
– Jorge B.