>首先,首先,您需要一个数据库连接。 假设您已经使用
。mysqli_connect()
<code class="php"><?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(); ?></code>
>使用PDO:
<code class="php"><?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(); } ?></code>pdo提供了一种更面向对象的方法。
>
记住,请记住将占位符值与您的实际数据库凭证和表格/列名称更换占位符。 至关重要的是,始终对其进行清理或更好的是在查询中使用它们之前的用户输入。>>在PHP 7?
>如何改善PHP 7应用程序中数据库查询的性能?
以上是如何在PHP 7中使用准备好的陈述?的详细内容。更多信息请关注PHP中文网其他相关文章!