Top Questions

  • 5.11 Years

    • Category : Php
    • Location : Chandigarh, India
    • Posted On : Jan 10, 2018

    PHP you can easily do this using the mysqli_connect() function. All communication between PHP and the MySQL database server takes place through this connection. The basic syntaxes for connecting to MySQL using MySQLi and PDO extensions:

    Syntax: MySQLi, Procedural way
    $con = mysqli_connect("hostname", "username", "password", "database");
    Syntax: MySQLi, Object Oriented way
    $con = new mysqli("hostname", "username", "password", "database");
    Syntax: PHP Data Objects (PDO) way
    $pdo = new PDO("mysql:host=hostname;dbname=database", "username", "password"); 
    Example (mysqli)

    Perform queries against the database:
    <?php
    $con=mysqli_connect("localhost","your_user","your_password","your_db");
    // Check connection
    if(mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    
    // Perform queries
    mysqli_query($con,"SELECT * FROM yourtable");
    mysqli_query($con,"INSERT INTO yourtable (FName,LName,Age)
    VALUES ('Glen','Quagmir',65)");
    
    mysqli_close($con);
    ?> 
    Example (PDO)

    Perform queries against the database:
    <?php
    $servername = "localhost";
    $username = "your_username";
    $password = "your_password";
    $dbname = "your_DBPDO";
    
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        // prepare sql and bind parameters
        $stmt = $conn->prepare("INSERT INTO yourGuests (ftname, lname, email)
        VALUES (:ftname, :lname, :email)");
        $stmt->bindParam(':ftname', $firstname);
        $stmt->bindParam(':lname', $lastname);
        $stmt->bindParam(':email', $email);
    
        // insert a row
        $firstname = "John";
        $lastname = "Doe";
        $email = "john@domain.com";
        $stmt->execute();
    
        // insert another row
        $firstname = "Julie1";
        $lastname = "Dooley1";
        $email = "julie1@domain.com";
        $stmt->execute();
    
        echo "New records added successfully";
        }
    catch(PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }
    $conn = null;
    ?> 
     

Add Your Answer

When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
Let's work to help developers, not make them feel stupid.