duanpen9294 2018-10-16 20:57
浏览 511

在MySQL中使用生成的字符串和变量

I need to use a generated string as an array within a MySQL-Loop. The string/array is built into $argumentarray from the $rows arguments and should after be used as the array of multiSQLarray[]

The function is called as:

multiSQL('**id,title,description,link**','menu')

The string gets correctly generated as

array('id' => $result['id'],'title' => $result['title'],'description' => $result['description'], 'link' => $result['link'])

But instead of using it as a string for the array it just adds it to the array for every result from the sql

Array ( [0] => array('id' => $result['id'],'title' => $result['title'],'description' => $result['description'], 'link' => $result['link']) [1] => array('id' => $result['id'],'title' => $result['title'],'description' => $result['description'], 'link' => $result['link']) ) 

What i expect is the SQL result as the array

Array ( [0] => Array ( [id] => 1 [title] => Customers [description] => Display the Customer Dashboard [link] => index.php ) [1] => Array ( [id] => 2 [title] => Server [description] => Display all Servers [link] => servers.php ) )

My code:

function multiSQL($rows=null,$table=null,$select=null) {
    if(is_null($select)) {$filter="";} else { $filter = ' where '.$select; }
    global $pdo;
    $sql = 'SELECT '.$rows.' FROM '.$table.$filter.'';
    $connection =$pdo->prepare($sql);
    $connection->execute();
    $multiSQLarray = array();
    $arguments = explode(',',$rows);
    $argumentarray = "";
    $argumentscount=count($arguments);
    $loopcount = 1;
    foreach($arguments as $argument){

            if($loopcount==$argumentscount){
            $loopcount++;
            $argumentarray = $argumentarray.' \''.$argument.'\' => $result[\''.$argument.'\']';

            }
            else{
                $loopcount++;
            $argumentarray = $argumentarray.'\''.$argument.'\' => $result[\''.$argument.'\'],';
            }
    }
    $argumentarray = 'array('.$argumentarray.')';
    echo $argumentarray.'<br><br>';
    while ($result = $connection->fetch(PDO::FETCH_BOTH)) {
        //$multiSQLarray[] = array('id' => $result['id'], 'title'  => $result['title'], 'description'  => $result['description'], 'link'  => $result['link']);
        $multiSQLarray[] = $argumentarray;
        }
    print_r($multiSQLarray);
    return $multiSQLarray;
  • 写回答

1条回答 默认 最新

  • duanjie2940 2018-10-16 21:30
    关注

    Structured data is structured data. Be it in a string or an array. I can't make sense of some of your code. The arrays in strings... unless you are angling to use an eval. I think that bit confuses your question some.

    One thing you need to consider is how exposed you will be to SQL injection. Basically never trust the user right? So, you could do things like predfine, in code, the allowed columns. If the form submitted references something not whitelisted then stop! Also, have to think about escaping the user supplied values.

    I'd want my function to accept a known, arguments that make sense for what it needs passed in... Clean things up first and then pass some data types that make the most sense to the function. Maybe something like...

    /**
     * @param string $table
     * @param array $fields
     * @param array $criteria (key/value pairs where key is field and value is scalar)
     */
    function buildQuery($table, $fields, $criteria) {
    
        $where = [];
        $whereVals = [];
        foreach($criteria as $k => $v) {
            $where[] = "({$k} = ?)";
            $whereVals[] = $v;
        }
        $where = implode(' AND ', $where);
    
    
        $fields = implode(', ', $fields);
    
        $sql = "SELECT {$fields} FROM {$table} WHERE {$where}";
        //eg. SELECT id, name, bar FROM fooTable WHERE (id = ?) AND (name = ?)
    
        $query = $pdo->prepare($sql);
        $retval = $query->execute($whereVals);
    
        return $retval;
    }
    
    $response = buildQuery( 'fooTable', 
                            ['id', 'name', 'bar'], 
                            [   
                                'id' => 5, 
                                'name' => 'john'
                            ]);
    

    Maybe look at some frameworks or an ORM like Doctrine? Can see some good examples of OOP representations of a select statement. Makes dynamic query building a lot easier. End up with something DRYer too.

    评论

报告相同问题?

悬赏问题

  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上