MySQL Connection

It is very easy to connect to MySQL db, like Oracle connection.

  1. $link = mysql_connect(’server name’, ‘username’, ‘password’);<?php
    $link = mysql_connect(’localhost’, ‘root’, ‘duygu’);
    if (!$link) {
    die(’Could not connect: ‘ . mysql_error());
    }
    echo ‘Connected successfully’;
    mysql_close($link);
    ?>
  2. Use mysql_select_db(”test”,$link) function to select the database which we will use.
    <?php
    $link = mysql_connect(’localhost’, ‘root’, ‘duygu’);
    if (!$link) {
    die(’Could not connect: ‘ . mysql_error());
    }
    echo ‘Connected successfully<br>’;

    if (!mysql_select_db(”test”,$link)) {
    echo “Unable to select test: ” . mysql_error();
    exit;
    }

    mysql_close($link);
    ?>
  3. We will write our sql statement and to execute this statement use mysql_query($sql); function
    <?php
    $link = mysql_connect(’localhost’, ‘root’, ‘duygu’);
    if (!$link) {
    die(’Could not connect: ‘ . mysql_error());
    }
    echo ‘Connected successfully<br>’;
    if (!mysql_select_db(”test”,$link)) {
    echo “Unable to select test: ” . mysql_error();
    exit;
    }
    $sql = “SELECT * FROM myblog”;

    $result = mysql_query($sql);
    if (!$result) {
    echo “Could not successfully run query ($sql) from DB: ” . mysql_error();
    exit;
    }

    mysql_close($link);
    ?>

  4. Control if there is a data or not. If there is a data write it on the page.
    <?php
    $link = mysql_connect(’localhost’, ‘root’, ‘duygu’);
    if (!$link) {
    die(’Could not connect: ‘ . mysql_error());
    }
    echo ‘Connected successfully<br>’;

    if (!mysql_select_db(”test”,$link)) {
    echo “Unable to select test: ” . mysql_error();
    exit;
    }
    $sql = “SELECT * FROM myblog”;

    $result = mysql_query($sql);
    if (!$result) {
    echo “Could not successfully run query ($sql) from DB: ” . mysql_error();
    exit;
    }
    if (mysql_num_rows($result) == 0) {
    echo “No rows found, nothing to print so am exiting”;
    exit;
    }
    while ($row = mysql_fetch_assoc($result)) {
    echo $row["NAME"].” “;
    echo $row["LASTNAME"].”<br>”;
    }

    mysql_close($link);
    ?>