Thursday, 18 June 2015

PHP and MySQL Programming/Database Connectivity

  • You Must have to follow these 5 steps to to perform Database connectivity with php .
  • 1 Opening a Connection to a MySQL Database
  • 2 Creating a Query
  • 3 Retrieving data from a SELECT Query
  • 4 Closing a Database Connection
  • 5 Error Handling

Open Database connection

 $db = "database1";
 $link = mysql_connect("localhost", "username", "password");
 mysql_select_db($db, $link);

Creating a Query

// A Query without any returned data
 mysql_query ("INSERT INTO `table1` ('val1', 'val2')");
 // A Query with returned data
 $query = mysql_query("SELECT 
 Retrieving data from a SELECT Query * FROM `table1`");

Retrieving data from a SELECT Query

# --- Connect To Database ---
 $db = "db1";
 $link = mysql_connect("localhost", "user", "pass");
 mysql_select_db($db, $link);
 
 # --- Select Info from Database ---
 $result = mysql_query ("SELECT val1, val2 FROM tbl1");

//This will simply output the result in table-like format.
 while ($row = mysql_fetch_row($result)){
    foreach ($row as $field) {
       print "$field . ";
    }
    print "";
 }

Closing a Database Connection

  mysql_close();

Error Handling

print mysql_error();


No comments:

Post a Comment