>首先,首先,您需要一個數據庫連接。 假設您已經使用
。mysqli_connect()
<?php $conn = mysqli_connect("localhost", "your_username", "your_password", "your_database"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Prepare the statement $stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?"); // Bind parameters. 's' indicates string type. Adjust as needed for other data types (i, d, b). $stmt->bind_param("ss", $username, $password); // Assign values to parameters $username = $_POST['username']; $password = $_POST['password']; //Important: NEVER directly use user input without sanitization. Consider password hashing instead of storing plain text passwords! // Execute the statement $stmt->execute(); // Bind result variables $stmt->bind_result($id, $username, $email, $password); //Replace with your actual column names // Fetch results while ($stmt->fetch()) { echo "ID: " . $id . "<br>"; echo "Username: " . $username . "<br>"; echo "Email: " . $email . "<br>"; // Avoid echoing the password! } // Close the statement and connection $stmt->close(); $conn->close(); ?>
>使用PDO:
<?php $dsn = 'mysql:host=localhost;dbname=your_database'; $user = 'your_username'; $password = 'your_password'; try { $pdo = new PDO($dsn, $user, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password"); $stmt->execute([ ':username' => $_POST['username'], ':password' => $_POST['password'], //Again, NEVER use raw user input directly for passwords. Hash them! ]); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($results as $row) { echo "ID: " . $row['id'] . "<br>"; echo "Username: " . $row['username'] . "<br>"; echo "Email: " . $row['email'] . "<br>"; // Avoid echoing the password! } } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } ?>
>
記住,請記住將佔位符值與您的實際數據庫憑證和表格/列名稱更換佔位符。 至關重要的是,始終對其進行清理或更好的是在查詢中使用它們之前的用戶輸入。 >>在PHP 7?
>如何改善PHP 7應用程序中數據庫查詢的性能?
以上是如何在PHP 7中使用準備好的陳述?的詳細內容。更多資訊請關注PHP中文網其他相關文章!