First is a modern set of a non-WordPress techniques using a mysqli prepared statement with an unknown number of values in an array. The second snippet will be the WordPress equivalent.
Let's assume that the indexed array of input data is untrusted and accessible from $_GET['villes']
. A prepared statement is the modern standard and preferred by professional developers over old/untrusted escaping techniques. The snippet to follow will return rows that have one of the ville
values specified in the array. If the array is not declared or is empty, it will return ALL rows in the database table.
Native PHP techniques:
$sql = "SELECT DISTINCT telecopie FROM comptage_fax";
if (!empty($_GET['villes'])) {
$count = count($_GET['villes']);
$commaDelimitedPlaceholders = implode(',', array_fill(0, $count, '?'));
$stmt = $conn->prepare("$sql WHERE ville IN ($commaDelimitedPlaceholders)");
$stmt->bind_param(str_repeat('s', $count), ...$_GET['villes']);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = $conn->query($sql);
}
From this point, you can access the rows of distinct telecopie
values (which is technically an iterable result set object) as if iterating an indexed array of associative arrays with a simple foreach()
.
foreach ($result as $row) {
echo $row['telecopie'];
}
With WordPress's helper methods the syntax is simpler because the variable binding and query execution is handled by get_results()
:
$sql = "SELECT DISTINCT telecopie FROM comptage_fax";
if (!empty($_GET['ville']) {
$commaDelimitedPlaceholders = implode(',', array_fill(0, count($_GET['ville']), '%s'));
$sql = $wpdb->prepare("$sql WHERE ville IN ($commaDelimitedPlaceholders)", $_GET['ville']);
}
$result = $wpdb->get_results($sql, ARRAY_A);
From this point, $result
is an indexed array of associative arrays -- specifically because of ARRAY_A
. $result
is not a result set object like in the first native php snippet. This means that you can use both classic looping language constructor or the full suite of array_
functions on the data.
Useful References: