sql >> Base de Datos >  >> RDS >> Mysql

Uso de claves y valores de matriz para crear una declaración de selección de sql

Puede construir un SQL Select simple así:

<?php


/**
 * @param array Column => Value pairs
 * @return string
 */
function create_sql_select(array $pair){
  $condition = array(); 

  foreach ( $pair as $key => $value){
    $condition[] = "{$key} = '{$value}'";
  } 

 // Separate by AND delimiter if there are more than 1 pair 
 $condition = join(' AND ', $condition);

 // Return prepared string:
 return "SELECT * FROM your_table WHERE {$condition}";
}

//Will print: SELECT * FROM your_table WHERE user = 'some' AND age = '10'
print create_sql_select(array('user' => 'some', 'age' => 10));