Menus

Showing posts with label php mysql select query. Show all posts
Showing posts with label php mysql select query. Show all posts

Tuesday, 9 January 2018

PHP - MySQL - Connection


MySQL Connection Using PHP Script

PHP provides mysql_connect() function to open a database connection.

Syntax

connection mysql_connect(server,user,passwd,new_link,client_flag);


Returns a MySQL link identifier on success or FALSE on failure.


Example

<?php
         $dbhost = 'localhost';
         $dbuser = 'test';
         $dbpass = 'Ii@21!abg';
         $conn = mysql_connect($dbhost, $dbuser, $dbpass);
         if(! $conn ) {
            die('Could not connect: ' . mysql_error());
         }
         echo 'Connected successfully<br>';

         $sql = 'SELECT id, name, course FROM std';

         mysql_select_db('ellorahs_test');
         $retval = mysql_query( $sql, $conn );
   
         if(! $retval ) {
              die('Could not get data: ' . mysql_error());
         }
   
         while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
            echo "ID :{$row['id']}  <br> ".
                 "Name : {$row['name']} <br> ".
                 "Course : {$row['course']} <br> ".
                 "--------------------------------<br>";
         } 
         echo "Fetched data successfully\n";

         mysql_close($conn);
?>


mysql_close()


Disconnect from the MySQL database anytime using another PHP function mysql_close().


SELECT command is used to fetch data from the MySQL database. 


Selecting a MySQL Database Using PHP

mysql_select_db to select a database. 
It returns TRUE on success or FALSE on failure.

Fetching Data Using a PHP


The SQL SELECT command is used to fetch data from the MySQL database.

SELECT command into a PHP function mysql_query().


mysql_fetch_array() can be used to fetch all the selected data.