I build a sql with dynamic value from a array. How can I use placeholder or that dymanic condition.
I'm calling that function like this: get_all_results("TABLE_NAME", ["column" => "VALUE"])
public static function get_all_results(string $table_name, array $where = []): array
{
global $wpdb;
/**
* Prepare condition
*
* @var string
*/
$condition = "";
$index = 0;
foreach ($where as $key => $value) {
if ($index > 0) {
$condition .= "AND ";
}
$condition .= "`$key` = '$value' ";
$index += 1;
}
if (!empty($condition)) {
$condition = " WHERE $condition ";
}
$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i {$condition} ", $table_name));
return $results;
}
How can I use $wpdb->prepare with my function or what should I do in this case ?
This line is the main problem for me, "Plugin Check" - plugin giving me error for this.
$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i {$condition} ", $table_name));
WordPress.DB.PreparedSQL.InterpolatedNotPrepared Line 238 of file includes/classes/DB.php.
Use placeholders and $wpdb->prepare(); found interpolated variable $condition at "SELECT * FROM %i WHERE $condition".
"SELECT * FROM %i WHERE $condition",
I will use placeholders for each value in the
$wherearray, in the below code that includes dynamically constructing the SQL query with placeholders for each condition, instead of directly inserting the condition string into the query. The actual values of these placeholders are then safely passed through$wpdb->prepare(), which effectively prevents SQL injection vulnerabilities, hope this helps