PHP function/procedure to bind question marks dynamically

后端 未结 2 1953
故里飘歌
故里飘歌 2021-01-15 12:02

I\'m fairly new to PHP. I\'m in need to bind the parameters in PDO by writing a custom function.

Say these are the 2 sqls I have.

sample_sql_1=\"sele         


        
2条回答
  •  星月不相逢
    2021-01-15 12:46

    You don't necessarily need bind_params(), you can just provide the values as an array to execute().

    See this example from the documentation:

    /* Execute a prepared statement by passing an array of insert values */
    $calories = 150;
    $colour = 'red';
    $sth = $dbh->prepare('SELECT name, colour, calories
        FROM fruit
        WHERE calories < ? AND colour = ?');
    $sth->execute(array($calories, $colour));
    

    Specifically for your case:

    // add a parameter for the values
    function pdo_db_query($query, $params = array()) {
        try {
        # MySQL with PDO_MYSQL
        $DBH = new dbconn(); // Create DB connection
    
        $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $DBH->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
        $STH = $DBH->prepare($query);
    
        // Execute the query with the given params
        $STH->execute($params);
    
        # setting the fetch mode
        $STH->setFetchMode(PDO::FETCH_ASSOC);
    
        // Create temporary array variable
        $json_arr = array();
    
        while ($row = $STH->fetch()) {
            $json_arr[] = $row;
        }
    
        # Close the connection
        $DBH = null;
    
        // Return the result set as a json
        echo json_encode($json_arr);
        } catch (PDOException $e) {
        echo $e->getMessage();
        var_dump($e->getMessage());
        }
    }
    

    To use this with a LIKE query:

    $query = "SELECT * FROM table WHERE field LIKE ?";
    $params = array( '%' . $searchvalue . '%' );
    $result = pdo_db_query( $query, $params );
    

提交回复
热议问题