Using array keys and values to create sql select statement

后端 未结 2 1430
轻奢々
轻奢々 2020-12-20 06:20

I am trying to pass a array that contains keys and values.

The keys are columns and values are the values to select.

I am trying to write a function where I

相关标签:
2条回答
  • 2020-12-20 06:48

    You can build a simple SQL Select like so:

    <?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));
    
    0 讨论(0)
  • 2020-12-20 06:52

    Use a foreach loop to iterate over the array and get key and value. Like this:

    $sql='';
    foreach($array as $key=>$value){
        $sql = sprintf("select * from table where %s = %s",$key,$value);
        print $sql;
    }
    
    0 讨论(0)
提交回复
热议问题