Beginner PHP MySQL Tutorials

In Web design, you can use PHP to connect to a MySQL database and use queries to use the information in its tables. The basic requirements of using PHP with MySQL involve connecting to the MySQL database, inserting new records into tables, and retrieving records from them. PHP has several functions to help you interact with MySQL databases on your Web page. When you extract information from MySQL, save them into PHP variables so you may format and display the information on your Web page in any way you choose, like any other variables.

Instructions

    • 1

      Open a new text file and insert the cursor at the top of the file.

    • 2

      Type the following:

      <?php

      $dbHost = "database_host_name";

      $dbUsername = "database_username";

      $dbPassword = "database_password";

      $dbName = "database_name";

      Subsitute the appropriate values for your MySQL database. These lines open a PHP tag and create four variables you use to establish a connection to a table in your MySQL database.

    • 3

      Type the following:

      $dbConn = mysql_connect ($dbHost, $dbUsername, $dbPassword) or die (Cannot connect to the database");

      mysql_select_db ($dbName);

      The first line create the connection to the MySQL database server, and the second line selects the database name.

    • 4

      Type the following:

      $insert = mysql_query("INSERT INTO table_name SET column1='value', column2='value', column3='value'");

      This inserts a new record into the table. If the table has more than three columns, those not specified in the query are filled in with default values.

    • 5

      Type the following:

      $query = mysql_query("SELECT * FROM table_name") or die(mysql_error());

      This line executes a SELECT query and saves the results into the $query variable. If the table specified by table_name does not exist, an error occurs and the query fails.

    • 6

      Type the following:

      $rowsNum = mysql_num_rows($query);

      echo $rowsNum . " records retrieved.\n";

      This function counts the number of records, or rows, that were returned in the select statement and then prints that number on the page.

    • 7

      Type the following:

      while($row = mysql_fetch_row($query)) {

      echo "$row[2]<br/>\n";

      }

      The mysql_fetch_row function gets a specific row from the $query variable and stores it in a temporary array variable called $row. The array uses zero-indexing, so the first column has index zero, the second column has index one and so on. These lines open a loop that gets each record returned from the SELECT query and prints the third column to the screen with a new line. Select which array indexes you need and format them on your page as needed.

    • 8

      Type the following:

      ?>

      This closes the PHP tag opened at the beginning. Save the file.

Related Searches:

References

Comments

Related Ads

Featured