简体   繁体   中英

Rewriting mysql_* with PDO (table-like content)

So I'm having a bit of trouble migrating from mysql_* functions to PDO-like statements. I have a table in which I output a different column for each row. However, I'm unsure as to how I could achieve this with 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');
                }
              }
        }

For example, how do I fetch everything from the type column in PDO?

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

Simple db class to get started:

<?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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM