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.

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

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了