简体   繁体   中英

Arrays in Drupal static queries

I have query in which I would like to pass the result of a MS SQL statement to a variable. Not sure how to do this.

My query:

 if($view->id() == 'program_search'  && 
  !empty($searched_miles_value) &&
  !empty($searched_zip_value) &&
  ($searched_miles_value != 'any')) {

    $connection = \Drupal\Core\Database\Database::getConnection();
    $result = $connection->query("SELECT to_zip FROM zipmaster_xref WHERE from_zip = '".$searched_zip_value."' AND miles = '".$searched_miles_value."'")-> fetchAll();

    $target_zips = $result ; //this line is not working
    foreach($result as $zip) {
      $target_zips[] = $zip->to_zip;
    }

    $query->addWhere('new_group', 'node__field_zip.field_zip_value', $target_zips, 'IN');

I want to pass the $result array into $target_zips and loop through it. Can any one help me to fix this?

Thanks!

before fetch your data you have to execute the query for example :

$result = $connection->query("SELECT to_zip FROM zipmaster_xref WHERE from_zip = '".$searched_zip_value."' AND miles = '".$searched_miles_value."'")->execute()->fetchAll();

But this usage is not correct at all.Passing variable to the query directly causing SQL Injection be avoid from this you should use placeholders read the documentations first please. An example for placeholders :

$query = $database->query("SELECT id, example FROM {mytable} WHERE created > :created", [
  ':created' => REQUEST_TIME - 3600,
]);

Drupal 8 static query documentation can be found at : https://www.drupal.org/docs/8/api/database-api/static-queries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM