How does PHP interact with MySQL databases in creating user profiles?
To create user profiles using PHP and MySQL, you need to establish a connection to the MySQL database, insert user data into the database, and retrieve user data when needed. This can be achieved by using PHP's MySQLi or PDO extension to interact with the database.
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert user data into the database
$username = "JohnDoe";
$email = "johndoe@example.com";
$sql = "INSERT INTO users (username, email) VALUES ('$username', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Retrieve user data from the database
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
// Close the database connection
$conn->close();
Keywords
Related Questions
- How can proper variable articulation and documentation improve code readability and understanding in PHP?
- Are there specific tools or techniques that can help developers address version-specific issues in PHP development?
- How can I improve my understanding of PHP to better implement features like image galleries on websites?