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.

    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容