用PDO重写mysql_ *(类似表格的内容)

时间:2015-03-12 21:15:17

标签: php mysql pdo

所以我在从 mysql _ * 函数迁移到类似PDO的语句时遇到了一些麻烦。我有一个表格,我在其中为每一行输出不同的列。但是,我不确定如何使用PDO实现这一目标。

        $SQL = "SELECT `id`, `email`, `information`, `type`, `language`, `status` FROM `requests`";
        $exec = mysql_query($SQL, $link);
           while ($row = mysql_fetch_array($exec)){
              echo "<tr class='tg-031e'>";
              echo "<td class='tg-031e'><input type='checkbox' name='checkbox[]' value=" . $row['id'] . "></form></td>";
              echo "<td class='tg-031e'>" . $row['email'] . "</td>";
              echo "<td class='tg-031e'><textarea readonly style='width:470px;height:80px;border:none;resize:none'>" . $row['information'] . "</textarea></td>";
              echo "<td class='tg-031e'>" . $row['type'] . "</td>";
              echo "<td class='tg-031e'>" . $row['language'] . "</td>";
              if(isset($_POST['checkbox'])){
                foreach($_POST['checkbox'] as $update_id){
                  $update_id = (int)$update_id;
                  $qR = "UPDATE requests SET status='✔' WHERE id=$update_id";
                  mysql_query($qR);
                                    header('Refresh: 1; URL=index.php');
                }
              }
        }

例如,如何从PDO中的type列中获取所有内容?

echo "<td class='tg-031e'>" . $row['type'] . "</td>";

1 个答案:

答案 0 :(得分:0)

简单的db类入门:

<?php 


class db {

    public static $db_host = "";
    public static $db_user = "";
    public static $db_pass = "";
    public static $db_name = "";

    public static function dbFactory() {
        $host = self::$db_host;
        if(strpos($host,":") !==false) {
            $parts = explode(":",$host);
            $hostname = "unix_socket=".$parts[1];
        } else {
            $hostname = "host=$host";
        }
        $user = self::$db_user;
        $pass = self::$db_pass;
        $dbase = self::$db_name;        
        $pdo = new PDO("mysql:$hostname;dbname=$dbase", $user, $pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);        
        return $pdo;
    }
}

$id = 115;

$pdo = db::dbFactory();
$stmt = $pdo->prepare("SELECT * FROM `tablename` WHERE `id` = :id ");
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($res);