Page 519 - Computer_Science_F5
P. 519

Computer Science  such as the MySQL server’s hostname, port number, and authentication credentials.
           Once connected, PHP can execute SQL statements to manage database operations.
           The following is an example using a farming database named “farming_db” with a
           table named “crops”:

          FOR ONLINE READING ONLY
           Connecting to a database
           PHP can be connected to database using MySQL. You can establish a connection to
           the MySQL database as shown in Program Example 8.6.


                  Program Example 8.6:

            PHP program to connect to a database

             php
             <button><svg><path></path></svg><span>Copy code</span><span></span></button>
             $serverName = “localhost”;
             $username = “root”;
             $password = “”;
             $databaseName = “farming_db”;

             // Create connection
             $conn = mysqli_connect($serverName, $username, $password, $databaseName);


             // Check connection
             if (!$conn) {
                 die(“Connection failed: “ . mysqli_connect_error());
             }
             echo “Connected successfully<br>”;


           2. Inserting data into the database
           Next, add a new crop record to the crops table. This will insert data into the database
           as shown in Program Example 8.7.


                   Program Example 8.7:

            PHP program to insert data to a database

             php
             <button><svg><path></path></svg><span>Copy code</span><span></span></button>
             $sql = “INSERT INTO crops (name, yield_per_hectare) VALUES (‘Wheat’, 4000)”;


                                                 510
                                                                for Advanced Secondary Schools



     Computer Science Form 5.indd   510                                                     23/07/2024   12:35
   514   515   516   517   518   519   520   521   522   523   524