0% found this document useful (0 votes)
15 views

Students Marklist Preparation Using Database Connection

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Students Marklist Preparation Using Database Connection

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Students Marklist Preparation Using Database Connection

Source Code:
<?php
// Define the database connection details
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'studentdb';

// Create the database connection


$conn = mysqli_connect($host,$user,$pass,$dbname);

// Check if the connection was successful


if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Create the students table


$sql = "CREATE TABLE IF NOT EXISTS students (
id INT(6),
name VARCHAR(30),
maths INT(3),
science INT(3),
english INT(3)
)";

if (mysqli_query($conn, $sql)) {
echo "Table students created successfully\n";
} else {
echo "Error creating table: " .mysqli_error($conn) . "\n";
}

// Insert example records into the students table


$sql = "INSERT INTO students (name, maths, science, english)
VALUES ('Alice', 85, 90, 80),
('Bob', 75, 80, 85),
('Charlie', 90, 85, 95),
('David', 70, 65, 75),
('Emma', 95, 95, 90)";

if (mysqli_query($conn, $sql)) {
echo "Records inserted successfully\n";
} else {
echo "Error inserting records: " .mysqli_error($conn) . "\n";
}

// Define the SQL query to fetch student data


$sql = "SELECT * FROM students";

// Execute the SQL query


$result = mysqli_query($conn, $sql);

// Check if there are any results


if (mysqli_num_rows($result) > 0) {
// Print the table header
echo "<table>";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Maths</th>";
echo "<th>Science</th>";
echo "<th>English</th>";
echo "<th>Total Marks</th>";
echo "<th>Average Marks</th>";
echo "</tr>";

// Loop through the results and print the marklist


while ($row = mysqli_fetch_assoc($result)) {
$name = $row["name"];
$maths = $row["maths"];
$science = $row["science"];
$english = $row["english"];
$total = $maths + $science + $english;
$average = $total / 3;

echo "<tr>";
echo "<td>$name</td>";
echo "<td>$maths</td>";
echo "<td>$science</td>";
echo "<td>$english</td>";
echo "<td>$total</td>";
echo "<td>$average</td>";
echo "</tr>";
}

// Print the table footer


echo "</table>";
} else {
echo "No results found.";
}
mysqli_close($conn);
?>

Output:

You might also like