Why db_connect () function returns Resource # 4 Warning: mysql_close (): 4 is not a valid MySQL-Link resource

require_once('common_use.php'); $connect_db = db_connect(); include_once $_SERVER['DOCUMENT_ROOT'] . '/views/home.html'; mysql_close($connect_db) or die(mysql_error()); 

Common_use.php file

  function db_connect(){ $server = 'localhost'; $username = 'root'; $password = ''; $dbname = 'newster'; $link = mysql_connect($server, $username, $password); if (!$link) { die('Невозможно соединиться с базой данных: ' . mysql_error()); } $db_selected = mysql_select_db($dbname); if (!$db_selected) { die ('Невозможно выбрать базу данных: ' . mysql_error()); } return $link; } 
  • you can at least quote in quotes or in a quote that you give out. Yes, and the question is why does it give you an error, or where does the resource “Resource №4” come from in the error code? - IVsevolod
  • one
    If you work with only one database, then you can not specify a handle. In this case, the last open / current connection is closed. PS And it would be time to switch to PDO;) - Deonis
  • Maybe $ connect_db is overridden somewhere. Try var_dump ($ connect_db) before mysql_close (); - istem

1 answer 1

Here Disassemble it better:

 class db { static $con; public static function connect() { $dbData = parse_ini_file($_SERVER['DOCUMENT_ROOT'].'/config.ini'); self::$con = mysql_connect($dbData['host'],$dbData['user'],$dbData['pass']); $db = mysql_select_db($dbData['db']); if ((!self::$con) || (!$db)) return 0; else return 1; } public static function deconnect() { if( !isset( self::$con ) ) return; mysql_close( self::$con ); } } 
  • 2
    Now the people will come and throws you pdo. ) - istem
  • no, well, the author uses mysql_ and therefore decided to help than he asks) In general, he was already told about mysql_ - Pavel Dura