2080 3

CSC329 ยท 2080 ยท 10 marks

Write a server side script in PHP to illustrate inserting and selecting values to and from database table. Create required connection using your own assumptions.

Write a server side script in PHP to illustrate inserting and selecting values to and from database table. Create required connection using your own assumptions.[10]

Web TechnologyChapter 6: Server Side Scripting using PHPWorking with PHP and MySQL

PHP Server-Side Script: Inserting and Selecting Values from Database

Assumptions

  • Server: localhost
  • Username: root
  • Password: `` (empty)
  • Database: webTech
  • Table: students with columns id, name, email, phone

Complete PHP Script

<?php

// Step 1: Database Connection
$servername = "localhost";
$username   = "root";
$password   = "";
$dbname     = "webTech";

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Step 2: Check Connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully  ";

// Step 3: Create Table (if not exists)
$createTable = "CREATE TABLE IF NOT EXISTS students (
    id     INT(6) AUTO_INCREMENT PRIMARY KEY,
    name   VARCHAR(50)  NOT NULL,
    email  VARCHAR(50)  NOT NULL,
    phone  VARCHAR(15)  NOT NULL
)";

if (mysqli_query($conn, $createTable)) {
    echo "Table ready.  ";
} else {
    echo "Error creating table: " . mysqli_error($conn) . " ";
}

// Step 4: INSERT values into the table
$name  = "Ram Sharma";
$email = "[email protected]";
$phone = "9841000000";

$insertSQL = "INSERT INTO students (name, email, phone)
              VALUES ('$name', '$email', '$phone')";

if (mysqli_query($conn, $insertSQL)) {
    echo "Record inserted successfully.  ";
} else {
    echo "Error inserting record: " . mysqli_error($conn) . " ";
}

// Step 5: SELECT values from the table
$selectSQL = "SELECT * FROM students";
$result    = mysqli_query($conn, $selectSQL);

// Step 6: Display the results
if (mysqli_num_rows($result) > 0) {
    echo " <strong>Records from students table:</strong> ";
    echo "<table border='1' cellpadding='5'>";
    echo "<tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
          </tr>";

    // Fetch each row and display
    while ($row = mysqli_fetch_assoc($result)) {
        echo "<tr>";
        echo "<td>" . $row["id"]    . "</td>";
        echo "<td>" . $row["name"]  . "</td>";
        echo "<td>" . $row["email"] . "</td>";
        echo "<td>" . $row["phone"] . "</td>";
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo "No records found.";
}

// Step 7: Close Connection
mysqli_close($conn);

?>

Step-by-Step Explanation

StepDescription
1Set server credentials (localhost, root, empty password, webTech DB)
2Use mysqli_connect() to create connection; check with if(!$conn)
3Create students table if it does not already exist
4Write INSERT SQL query and execute using mysqli_query()
5Write SELECT SQL query (SELECT * FROM students) and execute
6Use mysqli_num_rows() to check if rows exist; loop with mysqli_fetch_assoc() to display each row
7Close connection using mysqli_close()

Expected Output

Connected successfully
Table ready.
Record inserted successfully.

Records from students table:
+----+------------+-----------------+------------+
| ID | Name       | Email           | Phone      |
+----+------------+-----------------+------------+
|  1 | Ram Sharma | [email protected] | 9841000000 |
+----+------------+-----------------+------------+

Note: The procedural approach uses mysqli_connect() for connection and mysqli_query() for executing SQL statements. The die() function stops execution if the connection fails, so no else block is needed after it.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.