【问题标题】:mysqli to PDO Translationmysqli 到 PDO 的翻译
【发布时间】:2014-11-06 11:29:25
【问题描述】:

以下代码对我来说至少是直截了当的。我想使用 PDO 来实现同样的目标。然而,尽我所能,我根本无法理解这个概念。有人可以解释一下吗?

//Connect to a database.
$link  = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die("Couldn't connect to database.");

//Delete from the multiple tables. 
$sql = "DELETE FROM table1, table2, tables3, tables4 WHERE id='75'";
$result = mysqli_query($link , $sql);

【问题讨论】:

    标签: php mysql database pdo mysqli


    【解决方案1】:

    在这里,使用准备好的语句只是为了显示为 id = 75 不是用户输入 - 但这是更好的方法和使用事务 - 如果您想一次删除/更新/插入更多数据,这是一种方式更快。

    $id = 75;
    
    
    try {
        $pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME , DB_USER, DB_PASS);
    
    
    
    
    $pdo->beginTransaction();
    
    $st = $pdo->prepare('DELETE FROM table1 WHERE id = :id');
    $st->execute(array(':id', $id));
    $st = $pdo->prepare('DELETE FROM table2 WHERE id = :id');
    $st->execute(array(':id', $id));
    $st = $pdo->prepare('DELETE FROM table3 WHERE id = :id');
    $st->execute(array(':id', $id));
    $st = $pdo->prepare('DELETE FROM table4 WHERE id = :id');
    $st->execute(array(':id', $id));
    
    $pdo->commit();
        }
    catch (PDOException $e) {
    
        die('Error!: ' . $e->getMessage() . '<br/>');
    
    }
    

    旁注:

    要少写,可以这样:

    $array = array('table1','table2','table3','table4');
    foreach ($array as $table) {
    $st = $pdo->prepare('DELETE FROM '.$table.' WHERE id = :id');
        $st->execute(array(':id', $id));
    }
    

    【讨论】:

    • 非常感谢,我现在清楚多了。速记绝对是可取的。我一直喜欢经济代码。
    【解决方案2】:

    您不能在单个查询中执行多个表删除尝试在 PDO 中使用 foreach

    $pdo = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
    $tables = array("table1","table2","table3","table4");
    foreach($tables as $table) {
      $sql = "DELETE FROM $table WHERE id = :id";
      $stmt = $pdo->prepare($sql);
      $stmt->bindParam(':id', $id);  // $id or '75'
      $stmt->execute();
    }
    

    【讨论】:

    • 非常感谢。不能进行多次删除的包装器。所以这是进步?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多