Mysql
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Mysql

Làm thế nào để chuyển đổi mã MySQL thành câu lệnh PDO?

Tạo kết nối

Trước tiên, bạn cần thay thế mysqli của mình kết nối với PDO một (hoặc ít nhất thêm PDO kết nối cùng với mysqli một!).

// Define database connection parameters
$db_host = "127.0.0.1";
$db_name = "name_of_database";
$db_user = "user_name";
$db_pass = "user_password";


// Create a connection to the MySQL database using PDO
$pdo = new pdo(
    "mysql:host={$db_host};dbname={$db_name}",
    $db_user,
    $db_pass,
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => FALSE
    ]
);

Cập nhật mã của bạn

Các câu lệnh được soạn sẵn với mysqliPDO

Hầu như luôn luôn tốt hơn nếu sử dụng các câu lệnh chuẩn bị sẵn khi đưa dữ liệu biến vào một truy vấn SQL. Nó không chỉ an toàn hơn (nếu dữ liệu đến từ bất kỳ loại đầu vào nào do người dùng tạo) mà còn giúp dễ đọc hơn và dễ dàng chạy nhiều lần với các giá trị khác nhau.

Truy vấn được chuẩn bị với mysqli :

$sql   = "SELECT column1, column2 FROM table WHERE column3 = ? AND column4 = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("si", $string_condition, $int_condition);
$query->execute();
$query->store_result();
$query->bind_result($column1, $column2);
$query->fetch();

echo "Column1: {$column1}<br>";
echo "Column2: {$column2}";

Truy vấn chuẩn bị với PDO :

$sql   = "SELECT column1, column2 FROM table WHERE column3 = ? AND column4 = ?";
$query = $pdo->prepare($sql);
$query->execute([$string_condition, $int_condition]);
$row   = $query->fetchObject();
# $row = $query->fetch(); // Alternative to get indexed and/or associative array

echo "Column1: {$row->column1}<br>";
echo "Column2: {$row->column2}";

Mã đã cập nhật

// Using the NULL coalescing operator here is shorter than a ternary
$id = $_SESSION['u_id'] ?? NULL;

if($id) {
    $sql   = "SELECT email FROM users WHERE u_id = ?";
    $query = $pdo->prepare($sql);    // Prepare the query
    $query->execute([$id]);          // Bind the parameter and execute the query
    $email = $query->fetchColumn();  // Return the value from the database
}

// Putting "$email" on a line by itself does nothing for your code. The only
// thing it does is generate a "Notice" if it hasn't been defined earlier in
// the code. Best use:
//    - The ternary operator: $email = (isset($email)) ? $email : "";
//    - The NULL coalescing operator: $email = $email ?? "";
//    - OR initialize it earlier in code, before the first `if`, like: $email = "";
// N.B. Instead of "" you could use NULL or FALSE as well. Basically in this case 
//    anything that equates to BOOL(FALSE); so we can use them in `if` statements
//    so the following (2 commented lines and 1 uncommented) are effectively
//    interchangeable.
$email = $email ?? "";
# $email = $email ?? FALSE; 
# $email = $email ?? NULL;

// Presumably you will also want to change this function to PDO and prepared statements?
// Although it doesn't actually do anything in the code provided?
$suggestions = selectAll($table);  

// Same as with email, we're just going to use the NULL coalescing operator.
// Note: in this case you had used the third option from above - I've just
//   changed it so there is less bloat.
$optionOne     = $_POST['optionOne'] ?? "";
$optionTwo     = $_POST['optionTwo'] ?? "";
$newSuggestion = $_POST['new-suggestion'] ?? "";

// There's no point nesting `if` statements like this when there doesn't appear to be any
// additional code executed based on the out come of each statement? Just put it into one.
// We now don't need to use empty etc. because an empty, false, or null string all.
// equate to FALSE.
if($newSuggestion && $id && $email && $optionOne && $optionTwo) {
    // Not sure why you've made the the table name a variable UNLESS you have multiple tables
    // with exactly the same columns etc. and need to place in different ones at different
    // times. Which seems unlikely so I've just put the table name inline.
    $sql   = "INSERT INTO suggestions (user_id, email, option_1, option_2) VALUES (?, ?, ?, ?)";
    $query = $pdo->prepare($sql);
    $query->execute([$id, $email, $optionOne, $optionTwo]);
}
else{
    echo "All options must be entered";
}

Không có nhận xét

$id = $_SESSION['u_id'] ?? NULL;

if($id) {
    $sql   = "SELECT email FROM users WHERE u_id = ?";
    $query = $pdo->prepare($sql);
    $query->execute([$id]);
    $email = $query->fetchColumn();
}
$email       = $email ?? "";
$suggestions = selectAll($table);  

$optionOne     = $_POST['optionOne'] ?? "";
$optionTwo     = $_POST['optionTwo'] ?? "";
$newSuggestion = $_POST['new-suggestion'] ?? "";

if($newSuggestion && $id && $email && $optionOne && $optionTwo) {
    $sql   = "INSERT INTO suggestions (user_id, email, option_1, option_2) VALUES (?, ?, ?, ?)";
    $query = $pdo->prepare($sql);
    $query->execute([$id, $email, $optionOne, $optionTwo]);
}
else{
    echo "All options must be entered";
}



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. PHP &MySQL:Chuyển đổi TIMESTAMP đã lưu trữ thành múi giờ cục bộ của người dùng

  2. MySQL - Cập nhật nhiều giá trị và Ở ĐÂU TRONG

  3. Bảng dọn dẹp MySQL khỏi các mục nhập trùng lặp VÀ liên kết lại FK trong bảng tùy thuộc

  4. tập lệnh mẫu php để phân trang

  5. MySQL date hay PHP time?