dpevsxjn809817 2018-02-08 11:09
浏览 37
已采纳

从MySQLi转换为

I have a generic script that I use when running queries on a database, which encompasses error checking and the like. Hopefully, this is a readable enough script.

// Set some variables if necessary
$var = "example";

// Write sql statement with ? as placeholders for any values
$sql = "sqlstatementhere";

// Prepare the SQL statement using the database connection parameter
if($stmt = $dbconEDB->prepare($sql))
{
    // Bind any necessary variables 
    if($stmt->bind_param('s', $var))
    {
        $result = $stmt->execute();

        // If the statement ran successfully
        if($result)
        {
            $result = $stmt->get_result();

            if($result->num_rows >= 1)
            {
                while($row = $result->fetch_assoc())
                {
                    // If there are result get them here
                    // $var = $row['fieldname'];
                }
            }
            else // the statement returned 0 results
            {
                // Deal with the nothingness
            }
        }
        else // the sql didnt execute
        {
            // Somethings gone wrong here
        }
    }
    else // the binding was wrong
    {
        // Check your bindings
    }   
}
else // There was an error preparing the sql statement (its wrong)
{
    // the sql is wrong
}

I want to make the same kind of thing with PDO, however, would it be more beneficial to just make a Class?

  • 写回答

1条回答 默认 最新

  • dongyuan1970 2018-02-08 18:33
    关注
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO:: PDO::FETCH_ASSOC);
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$var]);
    $rowset = $stmt->fetchAll();
    

    If you enable exceptions, you can simplify your code and skip checking for errors after every function. If errors happen, you'll know about it! You probably want to catch the exceptions though.

    No need for bind_param() nonsense. Just pass an array of parameter values to execute().

    Don't worry about checking if there were any rows. fetchAll() returns an empty array if there were no results. Unless you have a huge result set that won't fit in memory, just use fetchAll().

    I have no idea why anyone uses mysqli, ever. PDO is easier.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?