sarah
answered Apr 26 '23 00:00
Sure, here's an example of how to use a POST variable in a MySQLi query and echo the results:
Assuming you have a POST variable called username that contains the value you want to search for in the database, you can use the following code:
php
Copy code
<?php
// Create a new MySQLi instance
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check for connection errors
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
exit();
}
// Escape the POST variable to prevent SQL injection
$username = $mysqli->real_escape_string($_POST['username']);
// Build the query using the escaped username variable
$query = "SELECT * FROM users WHERE username = '$username'";
// Execute the query and get the result set
$result = $mysqli->query($query);
// Check for query errors
if (!$result) {
echo "Failed to execute query: " . $mysqli->error;
exit();
}
// Loop through the result set and echo the data
while ($row = $result->fetch_assoc()) {
echo "Username: " . $row['username'] . "<br>";
echo "Email: " . $row['email'] . "<br>";
// Add additional fields to echo as needed
}
// Free up resources
$result->free();
$mysqli->close();
?>
This code first creates a new MySQLi instance and checks for connection errors. It then escapes the POST variable using the real_escape_string() function to prevent SQL injection attacks. Next, it builds the query using the escaped variable and executes it, checking for any errors. Finally, it loops through the result set and echos the data for each row, and then frees up the resources and closes the MySQLi connection.