mysql_到pdo:我做得对吗?

时间:2017-06-29 10:43:51

标签: php mysql pdo driver

(browseroutput.jpg)

我刚刚将一个旧的mysql_* from教程改为PDO,并想知道我是否正确行事。 我没有得到mysql_*和PDO,他们是驱动程序还是只是获取数据的不同变体?

我的代码应该工作,但我有点怀疑它是否有效,因为我是初学者。

  <?php
  // New PDO variant   

  try {
     $user = "user";
     $pass = "";

     $pdo = new PDO('mysql:host=localhost;dbname=testdb', $user, $pass);

     //build query
     $age = $_GET['age'];
     $sex = $_GET['sex'];
     $wpm = $_GET['wpm'];

     $query = "SELECT * FROM ajax_example WHERE sex = '$sex'";

     if(is_numeric($age))
     $query .= " AND age <= $age";

     if(is_numeric($wpm))
     $query .= " AND wpm <= $wpm";

     $stmt = $pdo->prepare($query);

     $display_string = "<table>";
     $display_string .= "<tr>";
     $display_string .= "<th>Name</th>";
     $display_string .= "<th>Age</th>";
     $display_string .= "<th>Sex</th>";
     $display_string .= "<th>WPM</th>";
     $display_string .= "</tr>";

     $stmt->execute(array('name' => $name));

     foreach ($stmt as $row) {
        $display_string .= "<tr>";
        $display_string .= "<td>$row[name]</td>";
        $display_string .= "<td>$row[age]</td>";
        $display_string .= "<td>$row[sex]</td>";
        $display_string .= "<td>$row[wpm]</td>";
        $display_string .= "</tr>";
     }

     echo "Query: " . $query . "<br />";

     $display_string .= "</table>";
     echo $display_string;
     $dbh = null;

  } catch (PDOException $e) {
     print "Error!: " . $e->getMessage() . "<br/>";
     die();
  }
  ?>

2 个答案:

答案 0 :(得分:0)

您应该使用preparedstatement并使用?传递参数,例如:

$sth = $dbh->prepare('SELECT * FROM ajax_example WHERE sex = ?');
$sth->execute(array('male'));

查询和参数(显然)会根据$age$wpm的值而改变,但使用预准备语句和绑定参数将有助于防止SQL Injection

答案 1 :(得分:0)

你几乎是正确的,你只是错过了prepare()

的观点
<?php
// New PDO variant   
try {
    $user = "user";
    $pass = "";

    $pdo = new PDO('mysql:host=localhost;dbname=testdb', $user, $pass);

    //build query
    $age = intval($_GET['age']);
    $sex = $_GET['sex'];
    $wpm = intval($_GET['wpm']);

    $query = "SELECT * FROM ajax_example WHERE sex = ? AND age <= ? AND wpm <= ?";
    $stmt  = $pdo->prepare($query);

    $stmt->execute(array($sex,$age,$wpm));

    $results = $stmt->fetchall();
    if (count($results > 0)) {
        echo "<table>";
        echo "<tr>";
        echo "<th>Name</th>";
        echo "<th>Age</th>";
        echo "<th>Sex</th>";
        echo "<th>WPM</th>";
        echo "</tr>";
        foreach ($results as $row) {
            echo "<tr>";
            echo "<td>" . $row['name'] . "</td>";
            echo "<td>" . $row['age'] . "</td>";
            echo "<td>" . $row['sex'] . "</td>";
            echo "<td>" . $row['wpm'] . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    }else{

        echo "no results available";
    }
}
catch (PDOException $e) {
    echo "Error!: " . $e->getMessage() . "<br/>";

}
?>