Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • PDO connecting to mysql

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 134
    Comment on it

    Access data from mysql using PDO includes the following steps:

    • connect to a MySQL database:

      $db_conn = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);

    • create a select statement and then execute it by using query() method.

      $sql = 'SELECT * from tablename';

      $exec = $db_conn->query($sql);

    • set the fetch mode(PDO::FETCH_ASSOC) by using setFetchMode() method

      $q->setFetchMode(PDO::FETCH_ASSOC);

    • fetch each row by using fetch method of PDOstatement

    Example:

    $username="username";  //set username of database
    $password="password";  //set password of database
    $dbname="dbname"; //set database name
    $host="hostname"; //set hostname
        //connecting using PDO
        $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $sql = 'SELECT * from table1';
    $q = $conn->query($sql);
       //fetching data
    $q->setFetchMode(PDO::FETCH_ASSOC);
    while ($r = $q->fetch()){
        print_r($result);
    
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: