Php fatal error call to undefined function mysql_connect()

CP1251 и PHP 7 – как расшифровать непонятный набор символов

Иногда при написании сайта некоторые программисты используют не процедурный подход, являющийся на данный момент самым кратким решением, не раз доказавшим свою эффективность, а кодировку CP1251 и другие. В этом случае при переходе на PHP 7 на экране компьютера вся информация выглядит как непонятный набор палочек и иероглифов. В этом случае пробуем в файле дополнительной конфигурации .htaccess указать кодировку так.

Исправляем ситуацию в сайте, написанном при помощи CP1251

Проблемы с компьютером возникают нередко, и многие из них нужно научиться устранять самостоятельно. Например, это такие ситуации, как ошибка html5 Video file not found при просмотре видеороликов в сети или ошибки 0x0001, 0x0003 в дополнительной утилите Nvidia GeForce Experience.

Переводим сайт на MySQLi

Итак, вначале вносим коррективы в конструкцию, при помощи которой сайт подключается к базе данных. Открываем действующую запись.

  1. Везде mysql меняем на mysqli.
  2. В первой строчке после $password через запятую добавляем $dbname.
  3. Вторую строчку mysql_select_db($dbname, $link) убираем совсем.
  4. В третьей строчке перед ‘set names cp1251’ ставим $link и запятую.

Получается так.

В конструкцию, отвечающую за запросы, также вносим изменения. Берем действующую запись.

  1. Также заменяем mysql на mysqli.
  2. Меняем местами то, что заключено в скобки.

Теперь выглядит так.

Измененная конструкция, отвечающая за запросы

Открываем следующие популярные функции:

  • mysql_fetch_array(),
  • mysql_fetch_row(),
  • mysql_fetch_assoc(),
  • mysql_fetch_array(),
  • mysql_num_rows(),
  • mysql_insert_id(),
  • mysql_close().

И везде производим замену mysql на mysqli. Наша картина выглядит следующим образом.

Introduction

In this article, the focus is for solving an error message which appear upon accessing one of the service exist in the Docker container. Upon accessing the service which is a service running where it need to access the web platform, the page is showing the following error message :

Fatal error: Uncaught Error: Call to undefined function mysql_connect() in /var/www/html/wp-includes/wp-db.php:1564 Stack trace: #0 /var/www/html/wp-includes/wp-db.php(592): wpdb->db_connect() #1 /var/www/html/wp-includes/load.php(404): wpdb->__construct('wordpress', 'wordpress', 'wordpress', 'localhost') #2 /var/www/html/wp-settings.php(106): require_wp_db() #3 /var/www/html/wp-config.php(130): require_once('/var/www/html/w...') #4 /var/www/html/wp-load.php(37): require_once('/var/www/html/w...') #5 /var/www/html/wp-blog-header.php(13): require_once('/var/www/html/w...') #6 /var/www/html/index.php(17): require('/var/www/html/w...') #7 {main} thrown in /var/www/html/wp-includes/wp-db.php on line 1564

The above error message is showing that there is a missing library where it hold or it provide the function of ‘mysql_connect()’. Before going in further, the following is the ‘docker-compose.yml’ file where it is the base reference for building the Docker container providing the above web service. That content of ‘docker-compose.yml’ triggering the error exist below :

version: "3"
services:
  www:
     image: php:7.0-apache       
     ports:             
       - "80:80"         
     volumes:             
       - "./html:/var/www/html/"             
       - "./apache2:/var/log/apache2"         
     links:             
       - db         
     networks:             
       - default     
  db:         
    image: mysql         
    ports:             
      - "3306:3306"          
    environment:             
      MYSQL_DATABASE: wordpress             
      MYSQL_USER: wordpress             
      MYSQL_PASSWORD: wordpress             
      MYSQL_ROOT_PASSWORD: test         
    volumes:             
      - ./dump:/docker-entrypoint-initdb.d    
      - "./mysql:/var/lib/mysql"         
    networks:             
      - default     phpmyadmin:         
    image: phpmyadmin/phpmyadmin         
    links:             
      - db:db         
    ports:             
      - 9000:80         
    environment:             
      MYSQL_USER: user             
      MYSQL_PASSWORD: test             
      MYSQL_ROOT_PASSWORD: test 
    volumes:     
      persistent:

С чем связана ошибка Fatal error

Ошибка, начинающаяся словами Fatal error: Uncaught Error:, вызывает прекращение работы скрипта. В нашем случае она вместе с рядом других часто появляется при переводе старого сайта с PHP 5 на PHP 7. Выскакивают либо сообщения с уведомлениями об ошибках, либо просто висит белый экран. Здесь есть 2 пути – либо вернуть все назад, переключившись в панели управления хостингом, либо проявить настойчивость, разобраться с этой ошибкой и работать уже с новой версией PHP. Итак, давайте посмотрим, с чем же конкретно связана наша ошибка.

Как видно из самого названия ошибки, проблема связана с тем, что новые версии PHP (начиная с v. 5.5.0) не осуществляют поддержку оригинального расширения MySQL, в связи с чем сайт не собирает и не отправляет данные из БД. В этом случае разработчики предлагают перейти на расширения PDO или MySQLi. Попробуем выполнить несколько простых действий по переходу на MySQLi. Также пользователи иногда сталкиваются с ошибкой Error CertEnroll, возникающей в процессе создания запроса на выпуск сертификата на сайте “Росказна”.

17 Answers 17

You upgraded to PHP 7, and now mysql_connect is deprecated. Check yours with:

Change it to mysqli_connect as in:

If you’re upgrading legacy PHP, now you’re faced with the task of upgrading all your mysql_* functions with mysqli_* functions.

If you get this error after upgrading to PHP 7.0, then you are using deprecated libraries.

Open your terminal and run bellow command.

If you are running PHP you will also need to install the php module for mysql 5:

Verify that your installation of PHP has been compiled with mysql support. Create a test web page containing and load it in your browser. Search the page for MySQL. If you don’t see it, you need to recompile PHP with MySQL support, or reinstall a PHP package that has it built-in

Check if you forgot to enable the options below(loads the modules for mysql among others):

In PHP 7. You probably have PHP 7 in XAMPP. You now have two option: MySQLi and PDO.

This error is coming only for your PHP version v7.0. you can avoid these using PHP v5.0 else

i made only mysqli from mysql

I had this same problem on RHEL6. It turns out that the mysql.ini file in /etc/php.d only had a module name but needed a full path name. On my RHEL6 system the entry that works is:

After modifying the file, I restarted apache and everything worked.

A solution could be to use adapter functions like these to start using mysqli instead of mysql over your entire application:

Am using windows 8 n this issue got resolved by changing the environment variables

follow these steps: Open my computer properties->advanced system settings->Environment variables. Under ‘system variables’, select ‘path’ and click on ‘edit’ In ‘variable value’, add ‘C:\php;’ OR the path where php installed.

click OK and apply the settings and restart the system. It should work.

Here is a quick fix:

All the pros will probably hate me for this answer. But I got the same error on a server: Fatal error: Uncaught Error: Call to undefined function mysql_connect() that was using PHP 7. Did not have time to rewrite all the mysql code so a quick, temporary fix if anyone needs it is in CPANEL to look for PHP Configuration and change the version for that account to something like PHP 5.4 instead of PHP 7. Then the code worked fine without the above error.

How to Solve Error Message Fatal error: Uncaught Error: Call to undefined function mysql_connect()

In order to solve the problem, there is a specific step which is becoming a requirement in order to do it. The image for the ‘www’ must be going through some sort of modification. It is obvious since the image of the Apache Webserver in general has a default library settings and configuration. So, in order to do that, there must be a Dockerfile file which is describing the image for the ‘www’ service. Below is the actual content of the Dockerfile :

FROM php:7.2-apache
# Install stuff
RUN apt-get update && apt-get upgrade -y
RUN apt-get install sudo unzip wget -y
RUN docker-php-ext-install mysqli
# Configure stuff
RUN a2enmod rewrite
RUN a2enmod ssl
RUN service apache2 restart
EXPOSE 80

In the above Dockerfile content, there is an important line which is actually the solution for solving the problem. That line is exist as follows :

RUN docker-php-ext-install mysqli

In that line, there is a specific command for installing a library with the name of ‘mysqli’. Furthermore, since the image in this context is no longer the same default image of ‘php:7-2-apache, the ‘docker-compose.yml’ file can no longer use the ‘image’ definition for the service ‘www’. So, there is a slight revision on the content of the ‘docker-compose.yml’. Below is the revision of the content :

version: "3"
services:
  www:
     build: .       
     ports:             
       - "80:80"         
     volumes:             
       - "./html:/var/www/html/"             
       - "./apache2:/var/log/apache2"         
     links:             
       - db         
     networks:             
       - default

Do not forget to place the Dockerfile in the same directory in the same level with the ‘docker-compose.yml’ file. After that, just execute the command for building the Docker container once more. If there is no more error appear, the page will no longer display the previous error.

3 Answers 3

I was having this same issue, and most stackoverflow answers didn’t really clearly address this other step you need to take in setting up your php.ini. If you just uncomment extension=mysqli php still has no idea where any of your extensions are actually located, so it will fail to load them. Locate the section of your php.ini that looks something like:

And then uncomment the bottom “extension_dir” value and fill in the value with the absolute path of your “ext” directory, ie:

Once I completed these two steps (uncommenting extension=mysqli and then adding the absolute path in extension_dir), mysqli loaded correctly

As the setup say you have to rename one of those 2 you have, if you don’t PHP will go with defaults.

So change one of them to php.ini and uncomment the line – this should not really be needed as far as i recall.

For Windows, you can find the file in the C:\xampp\php\php.ini-Folder (Windows) or in the etc-Folder (within the xampp-Folder).

Under Linux, most distributions put lampp under /opt/lampp , so the file can be found under /opt/lampp/etc/php.ini .

If you can’t find it. Then you should rename one of those to php.ini file.

13 Answers 13

After looking at your phpinfo() output, it appears the mysql extensions are not being loaded. I suspect you might be editing the wrong php.ini file (there might be multiple copies). Make sure you are editing the php file at C:\php\php.ini (also check to make sure there is no second copy in C:\Windows).

Also, you should check your Apache logs for errors (should be in the \logs\ directory in your Apache install.

If you haven’t read the below, I would take a look at the comments section, because it seems like a lot of people experience quirks with setting this up. A few commenters offer solutions they used to get it working.

Another common solution seems to be to copy libmysql.dll and php_mysql.dll from c:\PHP to C:\Windows\System32.

Background about my (similar) problem:

I was asked to fix a PHP project, which made use of short tags. My WAMP server’s PHP.ini had short_open_tag = off . In order to run the project for the first time, I modified this setting to short_open_tag = off .

PROBLEM Surfaced: Immediately after this change, all my mysql_connect() calls failed. It threw an error

Solution: Simply set short_open_tag = off .

My PC is running Windows 7 (Apache 2.2 & PHP 5.2.17 & MySQL 5.0.51a), the syntax in the file “httpd.conf” (C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf\httpd.conf) was sensitive to slashes. You can check if “php.ini” is read from the right directory. Just type in your browser “localhost/index.php”. The code of index.php is the following:

There is the row (not far from the top) called “Loaded Configuration File”. So, if there is nothing added, then the problem could be that your “php.ini” is not read, even you uncommented (extension=php_mysql.dll and extension=php_mysqli.dll). So, in order to make it work I did the following step. I needed to change from

Pay the attention that the last slash disturbed everything!

Создание резервных копий сайта

Прежде чем предпринимать какие-либо серьезные попытки исправить Fatal error: Uncaught Error: Call to undefined function mysql_connect, необходимо создать резервные копии своего сайта и БД. Также для того, чтобы была неограниченная возможность экспериментировать, добавляем на хостинге еще один сайт и копируем туда файлы, в которые будем вносить различные корректировки. Подобный подход поможет избежать последствий необдуманных или неосторожных действий с данными – мы их уже не потеряем, т. к. они дополнительно хранятся в резервных копиях. Это актуально при решении различных задач, например, при отладке кода на JavaScript иногда приходится решать ошибку TypeError: Cannot read property ‘xxx’ of undefined.

Рейтинг
( Пока оценок нет )
Editor
Editor/ автор статьи

Давно интересуюсь темой. Мне нравится писать о том, в чём разбираюсь.

Понравилась статья? Поделиться с друзьями:
Сервис по настройке
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: