how to call a function multiple times with where clause in php pdo?

后端 未结 1 577
北海茫月
北海茫月 2021-01-16 19:59

I am new to php and trying hard to learn its why you guys and gals need to Forgive me for asking a lot!

Here is my question;

I am trying to call a function w

相关标签:
1条回答
  • 2021-01-16 20:29

    Nope, your function is not safe. Moreover it is just useless. There is no use case where you would use it like this getTable('posts');. And for the everything else it is much better to allow the full SQL syntax, not some limited subset.

    The simplest yet most powerful PDO function I can think of is a function that accepts a PDO object, an SQL query, and array with input variables. A PDO statement is returned. I wrote about such function in my article about PDO helper functions. So here is the code:

    function pdo($pdo, $sql, $args = NULL)
    {
        if (!$args)
        {
             return $pdo->query($sql);
        }
        $stmt = $pdo->prepare($sql);
        $stmt->execute($args);
        return $stmt;
    } 
    

    With this function you will be able to run any query, with any number of WHERE conditions, and get results in many different formats. Here are some examples from the article mentioned above:

    // getting the number of rows in the table
    $count = pdo($pdo, "SELECT count(*) FROM users")->fetchColumn();
    
    // the user data based on email
    $user = pdo($pdo, "SELECT * FROM users WHERE email=?", [$email])->fetch();
    
    // getting many rows from the table
    $data = pdo($pdo, "SELECT * FROM users WHERE salary > ?", [$salary])->fetchAll();
    
    // getting the number of affected rows from DELETE/UPDATE/INSERT
    $deleted = pdo($pdo, "DELETE FROM users WHERE id=?", [$id])->rowCount();
    
    // insert
    pdo($pdo, "INSERT INTO users VALUES (null, ?,?,?)", [$name, $email, $password]);
    
    // named placeholders are also welcome though I find them a bit too verbose
    pdo($pdo, "UPDATE users SET name=:name WHERE id=:id", ['id'=>$id, 'name'=>$name]);
    
    // using a sophisticated fetch mode, indexing the returned array by id
    $indexed = pdo($pdo, "SELECT id, name FROM users")->fetchAll(PDO::FETCH_KEY_PAIR);
    

    Special for you, here is the while example, though this method is considered clumsy and outdated:

    $stmt = pdo($pdo,"SELECT * FROM tableName WHERE field = ?",[$value]);
    while ($row = $stmt->fetch()) {
        echo $row['name'];
    }
    
    0 讨论(0)
提交回复
热议问题