PHP Fundamentals & Databases
Take your skills to the next level. Let's learn the essentials of connecting PHP to a MySQL database, SELECTING records, and INSERTING new ones seamlessly.
1. Connecting to the Database
Unlike HTML or CSS, PHP requires a backend server (like XAMPP's Apache) and a database (like MySQL). To communicate with the database, we use the `mysqli` component.
localhost), a username (default is root for local servers), a password, and the target database name.
<?php $host = 'localhost'; $username = 'root'; $password = ''; $dbname = 'codepath_db'; // Establish connection $conn = new mysqli($host, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
2. Fetching Data with SELECT FROM
To read data from a table, we use the SELECT statement. The FROM keyword specifies which table, and ORDER BY helps us sort.
SELECT * command fetches all columns. You run the query via $conn->query($sql) and then loop through the results checking num_rows > 0.
<?php $sql = "SELECT * FROM reviews ORDER BY created_at DESC"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "Name: " . $row['name']; } } else { echo "0 results"; } ?>
3. Saving Data with INSERT INTO
Adding new data to a table involves INSERT INTO. We define the columns we are inserting to and provide the VALUES. It is crucial to escape strings properly to prevent SQL injections.
$conn->real_escape_string() (or prepared statements) when taking user input from $_POST to save into a database securely.
<?php $name = $conn->real_escape_string($_POST['name']); $comment = $conn->real_escape_string($_POST['comment']); $sql = "INSERT INTO reviews (name, comment) VALUES ('$name', '$comment')"; $conn->query($sql); ?>
4. Live Example: Interactive Review System UI
Using the principles of CONNECT, INSERT, and SELECT we just learned, you would build HTML interfaces that POST to the PHP backend.
Leave a Course Review
$_POST superglobal variable array to then use an INSERT INTO database command.
Recent Reviews Example
I loved learning about PHP backend logic! The SELECT and INSERT commands make sense now.
Really solid examples explaining how to structure databases.