You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQLi转PDO后提交无响应,请求技术协助

Hey there! Let's walk through the issues in your PDO code and fix them up step by step — I can see where you got tripped up switching from MySQLi, it's super common to carry over old habits at first.

Key Issues in Your Current Code

  • SQL Injection Risks & Syntax Errors: You're directly inserting user input ($_POST['name'], etc.) into your SQL strings. This isn't just a huge security gap; if someone enters a character like a single quote, it'll break your query entirely.
  • Wrong Insert ID Syntax: $link->insert_id is MySQLi-specific. In PDO, you need to use $dbConn->lastInsertId() to get the ID of the most recently added row.
  • Prepared Statements Aren't Executed: For DELETE, UPDATE, and even your initial SELECT, you call prepare() but never run execute() — so none of those queries actually reach the database.
  • Broken Error Handling: When something fails, echoing $dbConn just outputs the PDO object, not the actual error message that would help you debug.
  • Nonsensical Variable Assignment: In your update block, $id =($dbConn); doesn't do anything useful — you already have the valid $id from $_POST['id'].

Fixed PDO Code

<?php 
$databaseHost = 'localhost'; 
$databaseName = 'test'; 
$databaseUsername = 'test'; 
$databasePassword = 'pass'; 

try { 
    // Add charset to DSN to avoid encoding issues
    $dbConn = new PDO("mysql:host={$databaseHost};dbname={$databaseName};charset=utf8mb4", $databaseUsername, $databasePassword); 
    $dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    // Explicitly set charset for older MySQL versions
    $dbConn->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8mb4");
} catch(PDOException $e) { 
    die("Database connection failed: " . $e->getMessage()); 
} 

// Handle saving new comment
if (isset($_POST['save'])) { 
    $name = $_POST['name']; 
    $comment = $_POST['comment']; 

    // Use prepared statements with placeholders to prevent SQL injection
    $sql = "INSERT INTO comments (name, comment) VALUES (:name, :comment)"; 
    $stmt = $dbConn->prepare($sql);
    // Bind parameters to placeholders
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':comment', $comment);
    
    if ($stmt->execute()) { 
        // Correct way to get last inserted ID in PDO
        $id = $dbConn->lastInsertId(); 
        // Use htmlspecialchars to prevent XSS attacks
        $saved_comment = '<div class="comment_box"> 
        <span class="delete" data-id="' . htmlspecialchars($id) . '" >delete</span> 
        <span class="edit" data-id="' . htmlspecialchars($id) . '">edit</span> 
        <div class="display_name">'. htmlspecialchars($name) .'</div> 
        <div class="comment_text">'. htmlspecialchars($comment) .'</div> 
        </div>'; 
        echo $saved_comment; 
    } else { 
        $errorInfo = $stmt->errorInfo();
        echo "Error saving comment: " . $errorInfo[2]; 
    } 
    exit(); 
} 

// Handle deleting a comment
if (isset($_GET['delete'])) { 
    // Validate input to ensure we get a valid integer ID
    $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
    if (!$id) {
        echo "Invalid comment ID";
        exit();
    }

    $sql = "DELETE FROM comments WHERE id = :id"; 
    $stmt = $dbConn->prepare($sql);
    $stmt->bindParam(':id', $id);
    $stmt->execute();
    exit(); 
} 

// Handle updating a comment
if (isset($_POST['update'])) { 
    $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
    $name = $_POST['name']; 
    $comment = $_POST['comment']; 

    if (!$id) {
        echo "Invalid comment ID";
        exit();
    }

    $sql = "UPDATE comments SET name = :name, comment = :comment WHERE id = :id"; 
    $stmt = $dbConn->prepare($sql);
    $stmt->bindParam(':id', $id);
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':comment', $comment);
    
    if ($stmt->execute()) { 
        $saved_comment = '<div class="comment_box"> 
        <span class="delete" data-id="' . htmlspecialchars($id) . '" >delete</span> 
        <span class="edit" data-id="' . htmlspecialchars($id) . '">edit</span> 
        <div class="display_name">'. htmlspecialchars($name) .'</div> 
        <div class="comment_text">'. htmlspecialchars($comment) .'</div> 
        </div>'; 
        echo $saved_comment; 
    } else { 
        $errorInfo = $stmt->errorInfo();
        echo "Error updating comment: " . $errorInfo[2]; 
    } 
    exit(); 
} 

// Retrieve and display all comments
$sql = "SELECT * FROM comments"; 
$stmt = $dbConn->prepare($sql);
$stmt->execute(); // Don't forget to run the prepared statement!

$comments = '<div id="display_area">'; 
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
    $comments .= '<div class="comment_box"> 
    <span class="delete" data-id="' . htmlspecialchars($row['id']) . '" >delete</span> 
    <span class="edit" data-id="' . htmlspecialchars($row['id']) . '">edit</span> 
    <div class="display_name">'. htmlspecialchars($row['name']) .'</div> 
    <div class="comment_text">'. htmlspecialchars($row['comment']) .'</div> 
    </div>'; 
} 
$comments .= '</div>'; 
?>

Extra Tips to Keep in Mind

  • Sanitize All Output: I added htmlspecialchars() around every piece of user-generated content when outputting it. This prevents XSS attacks, which are just as dangerous as SQL injection.
  • Validate User Input: Using filter_input() ensures you're getting the type of data you expect (like an integer for comment IDs) before running any database queries.
  • Charset Configuration: Adding utf8mb4 to your DSN ensures your database handles all Unicode characters (including emojis) correctly.
  • Exception Mode: You already set ERRMODE_EXCEPTION, which is perfect — this makes PDO throw detailed exceptions for critical errors, making debugging way easier.

内容的提问来源于stack exchange,提问作者Emre.K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:34:28