Skip to content
PHP Logo

How can the PHP script be modified to ensure that the user's name is successfully stored in the database and displayed?

The issue can be solved by ensuring that the user's name is properly sanitized before being stored in the database to prevent any potential SQL injection attacks. This can be done by using prepared statements with parameterized queries in PHP. Additionally, make sure to properly retrieve and display the user's name from the database to ensure it is displayed correctly on the webpage.

php
// Get the user's name from the form input
$user_name = $_POST['user_name'];

// Sanitize the user's name to prevent SQL injection
$user_name = mysqli_real_escape_string($conn, $user_name);

// Prepare a SQL statement with a parameterized query
$stmt = $conn->prepare("INSERT INTO users (name) VALUES (?)");
$stmt->bind_param("s", $user_name);

// Execute the statement to insert the user's name into the database
$stmt->execute();

// Retrieve the user's name from the database and display it on the webpage
$result = $conn->query("SELECT name FROM users WHERE id = $user_id");
$row = $result->fetch_assoc();
echo "User's Name: " . $row['name'];