Vir Vir - 4 months ago 13
SQL Question

How to write mysql_connect query instead of mysqli in php (phpMyAdmin 4.6.0)?

I am making an enhancement on our clients old website by adding a video gallery. I would like to write a

mysql_connect
query instead of
mysqli
query, because right now, when I tested below mysqli code in my wamp server its works fine and shows Database result on .php page.

When I upload
.php
page to server from cpanel it displays error "Fatal error: Class 'mysqli' not found in......" right now, we are not able to update our php/mysql (servers) both in cPanel because of huge database dependency (all configuration code written using mysql_connect).

We using something version 4.6. I know its not a good way but I have no option right now.

Configuration Code :

<?php
class imageGallery
{
private $sql, $query;
function __construct()
{
/* DB Connection */
$this->sql = new mysqli('localhost', 'root', '', 'mediagalleryfinaltest');
}
/*
|--------------------------------------------------------------------------
| Get Gallery
|--------------------------------------------------------------------------
*/
function getGalley()
{
if ($query = $this->sql->query("SELECT * FROM `media` ORDER BY media_id ASC ")) {
$rows = array();
while ($row = $query->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
} else {
return "Error";
}
}
}

/* Create Object */
$obj = new imageGallery();
?>

Answer

For the class you have shown, switching to mysql_* would look like this.

I changed the errorhandling a little, so it will give you a message if it fails to connect, will throw an error when the query is false etc., ask if you want to know something about the specific changes

You should really tell your customer to upgrade his php-version. Maybe tell him, adding new features takes a lot of additional time because the language has developed a lot and you are not used to this old stuff.

class imageGallery {

    private $sql;

    function __construct() {
        $this->sql = mysql_connect('localhost', 'root', '');
        if(!$this->sql){
            trigger_error(mysql_error());
        }
        $db_select = mysql_select_db('mediagalleryfinaltest');
        if(!$db_select){
            trigger_error(mysql_error());
        }
    }

    /**
     * @return array|string
     */
    function getGalley() {
        if ($query = mysql_query("SELECT * FROM `media` ORDER BY media_id ASC ", $this->sql)) {
            $rows = array();
            while ($row = mysql_fetch_assoc($query)) {
                $rows[] = $row;
            }
            return $rows;
        } else {
            trigger_error(mysql_error());
        }
    }

}
Comments