Rozbudowujemy nasz helper Arr – tym razem o funkcje tablicowe, które przydadzą się przy pracy z SQL. Zaczynajmy:
Metoda toSqlCNames:
<?php
class Arr{
//(...)
public static function toSqlCNames($array){
return "(".implode(', ', $array).')';
}
}
$keys = ['name', 'age'];
echo Arr::toSqlCNames($keys);
//(name, age)
Metody toSqlPlaceholders i toPDOPlaceholders:
<?php
class Arr{
//(...)
public static function toSqlPlaceholders($array, $placeholder="?"){
$array = array_map(fn()=> $placeholder, $array);
return "(".implode(', ', $array).')';
}
public static function toPDOPlaceholders($array){
$array = array_map(fn($el)=> ":$el", $array);
return "(".implode(', ', $array).')';
}
}
$keys = ['name', 'age'];
echo Arr::toSqlPlaceholders($keys);
//(?, ?)
echo Arr::toPDOPlaceholders($keys);
//(:name, :age)
Metoda toSqlVals:
<?php
class Arr{
//(...)
public static function toSqlVals($array_assoc){
return "(".implode(", ", array_values($array_assoc)).")";
}
}
$data = ['name' => 'John', 'age' => 30];
echo Arr::toSqlVals($data);
//(John, 30)
Metoda toSqlRaw:
<?php
class Arr{
//(...)
public static function toSQLRaw($array){
$keys = static::toSqlCNames(array_keys($array));
$vals = static::toSqlVals($array);
return [$keys, $vals];
}
}
$data = ['name' => 'John', 'age' => 30];
print_r(Arr::toSQLRaw($data));
//Array ( [0] => (name, age) [1] => (John, 30) )
Metody toSqlEscaped i toPDOEscaped:
<?php
class Arr{
//(...)
public static function toSqlEscaped($array){
$keys = static::toSqlCNames(array_keys($array));
$placeholders = static::toSqlPlaceholders(array_keys($array));
$real_vals = static::toSqlVals($array);
return [$keys, $placeholders, $real_vals];
}
public static function toPDOEscaped($array){
$keys = static::toSqlCNames(array_keys($array));
$placeholders = static::toPDOPlaceholders(array_keys($array));
$real_vals = static::toSqlVals($array);
return [$keys, $placeholders, $real_vals];
}
}
$data = ['name' => 'John', 'age' => 30];
print_r(Arr::toSqlEscaped($data));
//Array ( [0] => (name, age) [1] => (?, ?) [2] => (John, 30) )
print_r(Arr::toPDOEscaped($data));
//Array ( [0] => (name, age) [1] => (:name, :age) [2] => (John, 30) )