Search code examples
phpmysqlmysql-real-escape-string

My first database connection


I've bought a domain-hosting from a local company. Their customer service is pretty horrible.

My code for connecting to the database seems ok but still its not working. Here my code:

function __construct(){
    if(!@mysql_ping()){
        $this->db_connect();
    }
    $sql  = "SELECT value FROM settings WHERE field =  'auto_logout'";
    $res  = mysql_fetch_array($this->execute_single_query($sql));
    $this->LOGIN_DURATION = $res['value'];
}


private function db_connect(){
    // Mysql connect
    $link = @mysql_connect('localhost', 'created_who_has_all_prev', 'pass_note_my_cpanel_and_mysql_has_same_pass');

    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    //echo 'Connected successfully<br/>';
    // Mysql select db select --->
    $db_selected = mysql_select_db($this->DB, $link);
    if (!$db_selected) {
        die ('Can\'t use specified Database : ' . mysql_error());
    }
    //echo "<br/>Database Selected<br/>";
    return $link;
}

And this is the snapshot: enter image description here


Solution

  • Your main problem is that the link that you create isn't accessible. So, PHP tries to connect with defaults (apparently in your setup it means the user is root) and since it has no password, the connection fails which is the cause of most of your warning messages.

    The last warning is a consequence of the others.

    To fix this problem - as you haven't provided details of the actual parts that are executing the query - here is how to re-write your code so it works:

    $mysqli = new mysqli("localhost", "user", "password", "database");
    if ($mysqli->connect_errno) {
        echo "(".$mysqli->connect_errno.") ".$mysqli->connect_error;
    }
    
    $sql = "SELECT `value` FROM `settings` WHERE `field` = ?";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("s","auto_logout");
    
    if (!$stmt->execute()) {
        echo "(".$stmt->errno.") ".$stmt->error;
    }
    
    $res = $stmt->get_result();
    $row = $res->fetch_assoc();
    LOGIN_DURATION = $row['field'];