Page 521 - Computer_Science_F5
P. 521

Computer Science  the connection. Program Exampe 8.9 shows  how the complete  script looks like
           when you combine all  four parts:

                    Program Example 8.9:

          FOR ONLINE READING ONLY
            PHP program for all four parts
             php
             <button><svg><path></path></svg><span>Copy code</span><span></span></button>
             <?php
             $serverName = “localhost”;
             $username = “root”;
             $password = “”;
             $databaseName = “farming_db”;
             // Create a connection
             $conn = mysqli_connect($serverName, $username, $password, $databaseName);

             // Check connection
             if (!$conn) {
                 die(“Connection failed: “ . mysqli_connect_error());
             }
             echo “Connected successfully<br>”;
             // Insert a new crop
             $sql = “INSERT INTO crops (name, yield_per_hectare) VALUES (‘Wheat’, 4000)”;
             if (mysqli_query($conn, $sql)) {
                 echo “New crop record created successfully<br>”;
             } else {
                 echo “Error: “. $sql. “<br>” . mysqli_error($conn);
             }
             // Fetch and display all crops
             $sql = “SELECT id, name, yield_per_hectare FROM crops”;
             $result = mysqli_query($conn, $sql);
             if (mysqli_num_rows($result) > 0) {
                 while($row = mysqli_fetch_assoc($result)) {
                     echo “id: “. $row[“id”] . “ - Name: “ . $row[“name”] . “ - Yield per hectare: “ . $row[“yield_
             per_hectare”] . “kg<br>”;
                 }
             } else {
                 echo “0 results found<br>”;
             }
             // Close the connection
             mysqli_close($conn);
             ?>



                                                 512
                                                                for Advanced Secondary Schools



     Computer Science Form 5.indd   512                                                     23/07/2024   12:35
   516   517   518   519   520   521   522   523   524   525   526