Search code examples
phpmysqlresultset

Cannot acces the database value from PHP


I have connected to mySql database from php . I want to fetch details for two columns from it . When I try to access them , it outputs null. The same querystring works fine when I run in phpmyAdmin database tool.

Below is my code :

$servername = "mysql";
            $username = "$$$$$$$$$";
            $password = "%%%%%%%%%%";
            $databasename = 'blog';

            // Create connection
            $conn = new mysqli($servername, $username, $password, $databasename);

            // Check connection
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            } else {
                echo "Connected successfully";
            }



 $select_sql = "Select site_url from sites where id LIKE '%website1Modal%'";
            $result = $conn->query($select_sql);

            if ($result->num_rows > 0) {
              echo "in if loop";
               echo $result[0];
}

The above code does outputs : "Connected successfully" and "in if loop".

Can someone tell me what silly mistake I am doing ?


Solution

  • An if doesn't put you into a loop. The if is a control structure. Use a while to enter a loop and put the fetch inside so the results are accessible.

    Give this a try:

    $servername = "mysql";
    $username = "$$$$$$$$$";
    $password = "%%%%%%%%%%";
    $databasename = 'blog';
    // Create connection
    $conn = new mysqli($servername, $username, $password, $databasename);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } else {
        echo "Connected successfully";
    }
    $select_sql = "Select site_url from sites where id LIKE '%website1Modal%'";
    $result = $conn->query($select_sql);
    if ($result->num_rows > 0) {
        echo "in if control";
        while($row = $result->fetch_array()) { //this is optional; if only one row the while can be removed. e.g. $row = $result->fetch_array();
            echo 'in while loop';
            echo $row['site_url'];
        } //if removing while remove this as well
    }
    

    You can read more about the if and while controls here.

    http://php.net/manual/en/control-structures.if.php
    http://php.net/manual/en/control-structures.while.php

    Here's the manual entry for what query does.

    The important bit

    For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object.

    and because you have a mysqli_result object you need to send that to the fetch which will

    Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset.