convert mysql to pdo

后端 未结 1 657
半阙折子戏
半阙折子戏 2021-01-23 05:02

So i have a function thats supposed to handle all data execute operations: sql

function loadResult($sql)  
{      
    $this->connect();    
    $sth = mysql         


        
1条回答
  •  鱼传尺愫
    2021-01-23 05:59

    Since your existing function accepts a fully-formed SQL string, with no placeholders, you don't need to use prepare + bind. Your code as written should work fine, or you could use PDO::query() to execute the SQL in one step.

    If you want to use parameterised queries, then your loadResult function is going to have to change a bit, as is the way you write your SQL. The example SQL you give doesn't actually have anything in that could be turned into a parameter (column names and table names can't be parameters as discussed here), but I'll use an imaginary variation:

    // Get the todo tasks for a particular user; the actual user ID is a parameter of the SQL
    $sql = "SELECT * FROM mcms_todolist_tasks WHERE user_id = :current_user_id"; 
    // Execute that SQL, with the :current_user_id parameter pulled from user input
    $rows = $db->loadResult($sql, array(':current_user_id' => $_GET['user']));
    

    This is a nice secure way of putting the user input into the query, as MySQL knows which parts are parameters and which are part of the SQL itself, and the SQL part has no variables that anyone can interfere with.

    The simplest way of making this work with your existing loadResult function would be something like this:

    // Function now takes an optional second argument
    // if not passed, it will default to an empty array, so existing code won't cause errors
    function loadResult($sql, $params=array())  
    {      
        $this->connect();    
        $sth = $this->con->prepare($sql);  
        // pass the parameters straight to the execute call
        $sth->execute($params); 
        // rest of function remains the same...
    

    There are cleverer things you can do with parameterised queries - e.g. binding variables to output parameters, preparing a query once and executing it multiple times with different parameters - but those will require more changes to the way your calling code works.

    0 讨论(0)
提交回复
热议问题