MySQL-driven Web Site Construction (Cont.)

  1. Calling a PHP Script with Embedded SQL
  2. The following PHP program shows how to access the your-db database and the books table and list the book titles, each of which contains a substring $_POST[title] entered from the Web. If the substring $_POST[title] is empty, then list all titles. Everything printed from PHP is displayed on the browser.

    ~/public_html/course/515/3/ListTitles.php
    <html><body>
    <?php
    
    if ( $_POST['act'] == "List the titles" ) {
    
      /************************************************************
    
      This program shows how to list the book titles from the
        books table.
    
      To use this program, you need to create a table
        books by using the following command:
    
      mysql> create table books (
          ->   title   char(128),
          ->   ISBN    char(20) primary key,
          ->   price   real );
      Query OK, 0 rows affected (0.07 sec)
    
      *************************************************************/
    
      $username = "your-id@undcsmysql";
      $password = "your-pw";
      $database = "your-db";
      $host     = "undcsmysql.mysql.database.azure.com";
      $conn     = new mysqli( $host, $username, $password, $database );
    
      // Connect to the database.
      if ( $conn->connect_error )
        die( 'Could not connect: ' . $conn->connect_error );
    
      // Compose the query.
      $query  = "select title from books where ";
      $query  = $query . "title like '%$_POST[title]%'";
    
      // Execute the query.
      $result = $conn->query( $query );
      // Print the results row by row.
      if ( $result->num_rows > 0 )
        while( $row = $result->fetch_assoc( ) )
          echo $row['title'];
    
      // Close the database.
      $conn->close( );
    }
    
    elseif ( $_POST["act"] == "Help" ) {
      echo  "No help at this moment.";
    }
    else {
      echo  "No such option: $_POST[act]";
    }
    
    ?>
    </body></html>

  3. Testing the Exercise Thoroughly