Php ошибка fatal error call to undefined function

I am trying to call a function from another function. I get an error:

Fatal error: Call to undefined function getInitialInformation() 
in controller.php on line 24

controller.php file:

require_once("model/model.php"); 

function intake() {
    $info = getInitialInformation($id); //line 24
}

model/model.php

function getInitialInformation($id) {
    return $GLOBALS['em']->find('InitialInformation', $id);
}

Things already tried:

  1. Verified that the require_once works, and the file exists in the specified location.
  2. Verified that the function exists in the file.

I am not able to figure this out. Am I missing something here?

Eric Leschinski's user avatar

asked Jan 2, 2013 at 1:20

janenz00's user avatar

6

How to reproduce the error, and how to fix it:

  1. Put this code in a file called p.php:

    <?php
    class yoyo{
        function salt(){
        }
        function pepper(){
            salt();
        }
    }
    $y = new yoyo();
    $y->pepper();
    ?>
    
  2. Run it like this:

    php p.php
    
  3. We get error:

    PHP Fatal error:  Call to undefined function salt() in 
    /home/el/foo/p.php on line 6
    
  4. Solution: use $this->salt(); instead of salt();

    So do it like this instead:

    <?php
    class yoyo{
        function salt(){
        }
        function pepper(){
            $this->salt();
        }
    }
    $y = new yoyo();
    $y->pepper();
    
    ?>
    

If someone could post a link to why $this has to be used before PHP functions within classes, yeah, that would be great.

answered Mar 28, 2014 at 20:59

Eric Leschinski's user avatar

Eric LeschinskiEric Leschinski

145k95 gold badges412 silver badges332 bronze badges

7

This was a developer mistake — a misplaced ending brace, which made the above function a nested function.

I see a lot of questions related to the undefined function error in SO. Let me note down this as an answer, in case someone else have the same issue with function scope.

Things I tried to troubleshoot first:

  1. Searched for the php file with the function definition in it. Verified that the file exists.
  2. Verified that the require (or include) statement for the above file exists in the page. Also, verified the absolute path in the require/include is correct.
  3. Verified that the filename is spelled correctly in the require statement.
  4. Echoed a word in the included file, to see if it has been properly included.
  5. Defined a separate function at the end of file, and called it. It worked too.

It was difficult to trace the braces, since the functions were very long — problem with legacy systems. Further steps to troubleshoot were this:

  1. I already defined a simple print function at the end of included file. I moved it to just above the «undefined function». That made it undefined too.
  2. Identified this as some scope issue.

  3. Used the Netbeans collapse (code fold) feature to check the function just above this one. So, the 1000 lines function above just collapsed along with this one, making this a nested function.

  4. Once the problem identified, cut-pasted the function to the end of file, which solved the issue.

answered Jan 2, 2013 at 2:04

janenz00's user avatar

janenz00janenz00

3,3155 gold badges28 silver badges37 bronze badges

4

Many times the problem comes because php does not support short open tags in php.ini file, i.e:

<?
   phpinfo();
?>

You must use:

<?php
   phpinfo();
?>

egig's user avatar

egig

4,3155 gold badges29 silver badges50 bronze badges

answered Sep 26, 2013 at 21:08

JRivero's user avatar

JRiveroJRivero

911 silver badge3 bronze badges

I happened that problem on a virtual server, when everything worked correctly on other hosting.
After several modifications I realized that I include or require_one works on all calls except in a file.
The problem of this file was the code < ?php ? > At the beginning and end of the text.
It was a script that was only < ?, and in that version of apache that was running did not work

loki's user avatar

loki

9,6967 gold badges56 silver badges80 bronze badges

answered Aug 30, 2016 at 9:32

Asier Arizti's user avatar

0

This is obviously not the case in this Q,
but since I got here following the same error message I though I would add what was wrong with my code and maybe it will help some one else:

I was porting code from JS to PHP and ended up having a class with some public method.
The code that was calling the class (being code that originated from JS) looked something like:

$myObject.method(...)

this is wrong because in PHP it should look like this:

$myObject->method(...)

and it also resulted with «PHP Call to undefined function».

change to use -> and the problem was solved.

answered Dec 13, 2022 at 5:10

epeleg's user avatar

epelegepeleg

10.3k17 gold badges101 silver badges151 bronze badges

Presently I am working on web services where my function is defined and it was throwing an error undefined function.I just added this in autoload.php in codeigniter

$autoload[‘helper’] = array(‘common’,’security’,’url’);

common is the name of my controller.

answered Jun 9, 2017 at 10:00

user8136352's user avatar

1

Please check that you have <?PHP at the top of your code. If you forget it, this error will appear.

answered Sep 29, 2020 at 3:32

Hosein Abdollahipoor's user avatar

The majority of new web developers see the fatal error “Call to undefined function” in PHP code, and they are unsure of the cause. If you’re one of them, then continue reading this article to the end.

We encounter the uncaught error “Call to undefined function” when we define and call a user-defined function. There are numerous causes for this error, and in this post, we will explore them all and provide easy explanations to dispel all of your doubts.

However, before we go into the details of this article, you need first to comprehend what a function is and what we call it. So without further ado, let’s get started with the post.

Table of Contents
  1. How Do Functions Work in PHP?
  2. What Are the Reasons and Solutions For The “Call to Undefined Function” Fatal Error in PHP?
    1. 1. Misspell of Function Name
    2. 2. Not Using This with Function Name Within PHP Class
    3. 3. Use Include or Require Properly
    4. 4. Using Dot(.) Instead of Object Operator(->)

How Do Functions Work in PHP?

Similar to other programming languages, PHP has functions. A function is a separate code that processes additional input as a parameter before returning a value. In PHP, we have two types of functions Builtin functions and user-defined functions.

Builtin functions are the functions that PHP provides to us to use them. Actually, you seldom ever need to build your own function because there are already more than 1000 built-in library functions available for various purposes; all you need to do is call them as needed.

On the other hand, we can create our own functions, called user-defined functions. In the case of user-defined functions, there are two key aspects you need to understand:

  1. Creating a PHP Function
  2. Calling a PHP Function

Creating your own PHP function is pretty simple. Let’s say you want to create a PHP function that, when called, will display a brief message in your browser. The example below invokes the method printMessage() immediately after creating it.

The name of a function should begin with the keyword “function,” and all PHP code should be enclosed in “{ }” brackets, as seen in the example below:

Code

<html>


   <head>

      <title>PHP Function Page</title>

   </head>

   

   <body>

      

      <?php

         // Creating a PHP Function

         function printMessage() {

            echo "Welcome to My Website";

         }

         

         // Calling a PHP Function

         printMessage();

      ?>

      

   </body>

</html>

Output

Welcome to My Website

What Are the Reasons and Solutions For The “Call to Undefined Function” Fatal Error in PHP?

Following are the reasons for facing the “Uncaught Error: Call to undefined function“:

  1. Misspell of function
  2. Not using this with the function name
  3. Use include or require properly
  4. Using dot(.) instead of object operator(->)

1. Misspell of Function Name

To prevent “Call to undefined function“, always double-check the function name. Let’s look at a straightforward example to see what output the following code will return if the function name is misspelt:

Code

<?php

class myclass{

    function printMessage(){

      echo "Welcome to My Website";

    }

    function myfunction(){

        $this->printMessage();

    }

}

$myvar = new myclass();

$myvar->myfunctions();

?>

In this example, we write myfunctions() in place of myfunction(), which causes this error, so it is always better to double-check the spelling of functions to avoid this error.

2. Not Using This with Function Name Within PHP Class

We face a “call to an undefined function” when we don’t use $this with the function or property name of the class. For example:

Code

<?php

class myclass{

    function printMessage(){

      

    }

    function myfunction(){

        printMessage();

    }

}

$myvar = new myclass();

$myvar->myfunction();

?>

The $this keyword in PHP refers to the class’s current object. Using the object operator (->), the $this keyword gives you access to the current object’s attributes and methods.

Only classes have access to the $this keyword. Beyond the class, it doesn’t exist. You’ll see an error if you try to use $this outside of a class.

You only use the $ with this keyword when you want to access an object property. The property name is not used with the dollar sign ($).

We now rewrite the code that causes the abovementioned errors with this keyword and examines the results:

Code

<?php

class myclass{

    function printMessage(){

      echo "Welcome to My Website";

    }

    function myfunction(){

        $this->printMessage();

    }

}

$myvar = new myclass();

$myvar->myfunction();

?>

Output

Welcome to My Website

3. Use Include or Require Properly

When we create a namespace and include it in another file, we often face “Call to undefined function“. For example:

Code of main.php

include myfunction.php

<?php

    echo tempNamespaceprintMessage();

?>

Code of myfunction.php

<?php

    namespace tempNamespace {

        function printMessage() {

            return "Welcome to my Website"

        }

    }

?>

To avoid this error, we have to write include or require statements correctly and in the proper place. Now we write the above code again using the appropriate include statement.

Code of mymain.php

<?php

    include "myfunction.php";

    echo tempNamespaceprintMessage();

?>

Code of myfunction.php

<?php

    namespace tempNamespace {

        function printMessage() {

            return "Welcome to my Website";

        }

    }

?>

Output

Welcome to my Website

Most of the time, when the user doesn’t check the file name, writes the wrong namespace name, or doesn’t include the namespace correctly, then faces “Call to undefined function” in PHP.

4. Using Dot(.) Instead of Object Operator(->)

The PHP code syntax is different from other programming languages. So when you come from JS or any other Object Oriented language, we use the dot(.) operator to call a method on an instance or access an instance property. But in PHP, we access the members of the provided object using the object operator (->). For example:

Code

<?php

class myclass{

    function printMessage(){

      echo "Welcome to My Website";

    }

    function myfunction(){

        $this->printMessage();

    }

}

$myvar = new myclass();

// Use . operator in place of object operator ->

$myvar.myfunction();

?>

We can easily get rid of this error by just replacing the dot(.) with the object operator(->). For example:

Code

<?php

class myclass{

    function printMessage(){

      echo "Welcome to My Website";

    }

    function myfunction(){

        $this->printMessage();

    }

}

$myvar = new myclass();

// Use . operator in place of object operator ->

$myvar->myfunction();

?>

Output

Welcome to My Website

Conclusion

Finally, you arrive at a point after finishing this reading when you can quickly get rid of the “Call to undefined function“. We covered all the causes in this article and gave you all the solutions. In this circumstance, we provide you with straightforward examples to help you resolve this uncaught issue.

To summarise the article on “How to fix call to undefined function in PHP“, always first search for the PHP file containing the function definition. Next, confirm the file’s existence and check to see if the page had the necessary (or included) line for the file, as mentioned above. Ensure the absolute path in the require/include is accurate as well.

Double-check that the spelling of the required statement’s filename is correct. Use this keyword in class to refer to the same class function. Always check the syntax of your code; many times, users from different languages use the wrong operators.

Share this article with your fellow coders if you found it beneficial, and let us know in the comments below ⬇️ which solution you used to solve the uncaught error “Call to undefined function”.

Happy Coding! 🥳

Изучаю PHP. Начал писать простенький блог по урокам с geekbrains

function articles_all(){
       //Zapros
        $query = "SELECT * FROM articles ORDER BY id DESC";
        $result = mysqli_query($link, $query);
        
    if (!$result)
        die(mysqli_error($link));
    
    //Izvlekaem iz bd
    $n = mysqli_num_rows($result);
    $articles = array();
        
    for ($i = 0; $i < $n; $i++){
        $row = mysqli_fetch_assoc($result);
        $articles[] = $row;
    }
        return $articles;
}

Fatal error: Call to undefined function articles_all() in C:xampphtdocsblogindex.php on line 6
Ну в индексе вызывается функция. Пожалуйста, объясните проблему, чтоб я понял) Заранее спасибо


  • Вопрос задан

    более трёх лет назад

  • 6434 просмотра

Пригласить эксперта

Файл класса.

<?php
class Articless {
 public function articles_all(){
       //Zapros
        $query = "SELECT * FROM articles ORDER BY id DESC";
        $result = mysqli_query($link, $query);
        
    if (!$result)
        die(mysqli_error($link));
    
    //Izvlekaem iz bd
    $n = mysqli_num_rows($result);
    $articles = array();
        
    for ($i = 0; $i < $n; $i++){
        $row = mysqli_fetch_assoc($result);
        $articles[] = $row;
    }
        return $articles;
}
}

в ndex.php
подключаете:
include(‘classFileName.php’);

используете:

$articles = new Articless();

$articles->articles_all();

Fatal error: Call to undefined function articles_all() in C:xampphtdocsblogindex.php on line 6

Ругается, что ты обращаешся к несуществующей функции в 6ой строчке.
Возможно, ты забыл её за’include’ить?)


  • Показать ещё
    Загружается…

09 июн. 2023, в 01:21

10000 руб./за проект

09 июн. 2023, в 01:06

50000 руб./за проект

09 июн. 2023, в 00:36

1000 руб./за проект

Минуточку внимания

  John Mwaniki /   29 Nov 2021

I have seen it severally where PHP mysqli_connect() database connection worked perfectly well for months or years, then all of a sudden it stops working. On enabling PHP error reporting, or on checking for errors in the error_log file in the cPanel, you find the error below:

PHP Fatal error: Uncaught Error: Call to undefined function mysqli_connect() in /home/username/public_html/…

This can create a great inconvenience and affect your database-driven website negatively especially if you don’t visit it regularly.

As you can see from the error above, PHP doesn’t recognize the mysqli_connect() function. This usually happens when some changes are made on the server that affects the mysqli extension.

There are 2 ways of connecting PHP to MySQL database:

  • MySQLi extension
  • PDO (PHP Data Objects) extension

Earlier versions of PHP(before version 5) used the MySQL extension which became deprecated in 2012 and was replaced with the MySQLi extension. The «i» in MySQLi stands for improved.

MySQLi extension supports both object-oriented and procedural ways of connecting to the database.

Procedural way

$conn = mysqli_connect("hostname", "username", "password", "database");

Object-Oriented way

$conn = new mysqli("hostname", "username", "password", "database");

All you have to do is to replace the values in quotes above with your real database credentials where the hostname in most cases will be «Localhost», though it may differ in some instances. The «username» is the username of the user assigned to the database, «password» is the password of that user, and «database» is the name of the database you are connecting to.

Either of the above methods will enable communication between PHP and the MySQL database server to take place.

When the error above occurs, the first thing you should do is to check if the PHP MySQL extension module is being loaded.

To do so, simply echo the phpinfo() function. It will show you all the information about your installed PHP version.

<?php
echo phpinfo();
?>

On the PHP information page, scroll down to the section titled «mysqli». You should be able to see the enabled MySQLi library in the Client API library version row as shown below:

phpinfo() mysqli information

There are two libraries for connecting PHP to MySQL database:

  • MySQL native driver for PHP (mysqlnd)
  • MySQL Client Library (libmysql)

The extensions(mysqli or PDO_MySQL) can either use the mysqlnd or libmysql library to connect from PHP to MySQL.

The MySQL Client Library is a general-purpose client library, meaning it can be used across different languages. On the other hand, mysqlnd library is highly optimized for and tightly integrated into PHP. The mysqlnd library is the default library for PHP 5.4 and later versions. MySQL recommends using the MySQL native driver for PHP (mysqlnd) together with ext/mysqli or PDO_MySQL.

In our case from the above screenshot, you can see that mysqlnd is the enabled driver.

We can now scroll more down to the section titled «mysqlnd» for more information as in the screenshot below:

mysqlnd information in phpinfo()

From the last row(API Extensions) of the above table, you can see that both mysqli and pdo_mysql extensions are enabled. This way the database connection works perfectly with no error.

In the case where the database connection results in the undefined function mysqli_connect() error, then you will find that the phpinfo() page doesn’t have the «mysqli» and the «mysqlnd» sections.

The solutions to undefined function mysqli_connect() error

1. Upgrading to a later PHP version

In most of the cases that this has happened, I have found that changing PHP to a later version has always worked and fixed the issue. Let’s say for example your current PHP version is 7.0, you can change to a later PHP version such as PHP 7.4 or 8.0.

This personally fixed the issue for me the last time it happened to one of the websites I manage.

Here is a brief guide on how to check your website PHP version -> 3 Simple ways of checking your website PHP version

And here is a simple guide for upgrading the PHP version -> How to change the PHP version in cPanel

2. Changing mysqli_connect to new mysqli

Try changing your database connection from procedural to OOP, ie. change replace mysqli_connect to new mysqli. Though it is the OOP way, it doesn’t mean that you will have to change anything else in your PHP code. I have seen it severally where making this change fixed the error.

3. Installing the PHP MySQL extension

If you host the website by yourself, you can simply install the php-mysqli extension on Ubuntu by use of the command below:

sudo apt install php-mysqli

You will then be required to restart the apache server with the command below for it to take effect.

sudo service apache2 restart

4. Adding or uncommenting the line «extension=php_mysql.dll» in the php.ini file

If you host the server yourself, open the php.ini file and remove the semicolon in front of the line below:

;extension=php_mysqli.dll

So that it will be like below:

extension=php_mysqli.dll

If this line doesn’t exist, simply add it. After making the changes, save and restart your Apache server.

If your website is hosted by a hosting provider/company, and upgrading to a later PHP version or changing mysqli_connect to new mysqli doesn’t seem to work for you, simply contact the host with the error message and they will fix it for you.

That’s all for this article. It’s my hope that it was helpful for you.

  1. HowTo
  2. PHP Howtos
  3. Call to Undefined Function in PHP

Shraddha Paghdar
Oct 24, 2021

Call to Undefined Function in PHP

Many of you have encountered this error several times Fatal error: Call to undefined function function_name(). In today’s post, we are finding out how to unravel this error. But before we solve this problem, let’s understand how PHP evaluates the functions.

There are several ways to define functions and call them. Let’s say you write it in the function.php file and call it in the main.php file.

    // function.php
<?php
    namespace fooNamespace {
        function foo() {
            return "Calling foo"
        }
    }
?>
    // main.php
include function.php
<?php
    echo fooNamespacefoo();
?>

Namespaces are qualifiers that enable better management by grouping classes that work together to perform a task. It allows you to use the same name for multiple classes. It is important to know how PHP knows which element of the namespace is required by the code. PHP namespaces work quite a sort of a filesystem. There are 3 ways to access a file in a file system:

  1. Relative file name such as fooBar.txt. It will resolve to fooDirectory/fooBar.txt where fooDirectory is the directory currently busy directory.
  2. Relative path name such as subdirectory/fooBar.txt. It will resolve to fooDirectory/subdirectory/fooBar.txt.
  3. Absolute path name such as /main/fooBar.txt. It will resolve to /main/fooBar.txt.

Namespaced elements in PHP follow an equivalent principle. For example, a class name can be specified in three ways:

  1. Unqualified name/Unprefixed class name:Or,If the current namespace is foonamespace, it will always resolve to foonamespacefoo. If the code is a global, non-namespaced code, this resolves to foo.
  2. Qualified name/Prefixed class name:
    $a = new fooSubnamespacefoo();
    

    Or,

    fooSubnamespacefoo::staticmethod();
    

    If the present namespace is foonamespace, it will always resolve to foonamespacefooSubnamespacefoo. If the code is global, non-namespaced code, this resolves to fooSubnamespacefoo.

  3. Fully qualified name/Prefixed name with global prefix operator:
    $a = new foonamespacefoo();
    

    Or,

    foonamespacefoo::staticmethod();
    

    This always resolves to the literal name laid out in the code, foonamespacefoo.

Now suppose you define a class & call the method of a class within the same namespace.

<?php
    class foo {
        function barFn() {
          echo "Hello foo!"
        }
        function bar() {
            barFn();
            // interpreter is confused which instance's function is called
            $this->barFn();
        }
    }
    $a = new foo();
    $a->bar();
?>

$this pseudo-variable has the methods and properties of the current object. Such a thing is beneficial because it allows you to access all the member variables and methods of the class. Inside the class, it is called $this->functionName(). Outside of the class, it is called $theclass->functionName().

$this is a reference to a PHP object the interpreter created for you, which contains an array of variables. If you call $this inside a normal method in a normal class, $this returns the object to which this method belongs.

Steps to Resolve the Error of Calling to Undefined Function in PHP

  • Verify that the file exists. Find the PHP file in which the function definition is written.
  • Verify that the file has been included using the require (or include) statement for the above file on the page. Check that the path in the require/include is correct.
  • Verify that the file name is spelled correctly in the require statement.
  • Print/echo a word in the included file to ascertain if it has been properly included.
  • Defined a separate function at the end of the file and call it.
  • Check functions are closed properly. (Trace the braces)
  • If you are calling methods of a class, make sure $this-> is written.

Shraddha Paghdar avatar
Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

Проблема, с которой сталкиваются многие программисты после перевода площадки на современную версию PHP, — вероятная полная или частичная потеря работоспособности программного обеспечения на одном или нескольких сайтах площадки. Не предавайтесь панике, всё решаемо!

Использование функций mysql_connect(), mysql_select_db(), mysql_query() и т.д.

В PHP 7 разработчики отказались от расширения mysql, все использования функций расширения приводят к фатальной ошибке (Call to undefined function).

Использование функций mysql_connect(), mysql_select_db(), mysql_query() и т.д.

Использование функций mysql_connect(), mysql_select_db(), mysql_query() и т.д.

Как заменить неработающие функции mysql_connect(), mysql_select_db(), mysql_query()? Ошибка «PHP Fatal Error: Call to undefined function»

Решения проблемы есть и даже не одно!

Есть достойная альтернатива mysql — расширение mysqli. Функции расширения соответствуют старым (большая часть):

mysqli_fetch_array() //расширение mysqli
mysql_fetch_array()  //расширение mysql

1. Если у вас небольшой проект, вам будет несложно через поиск найти несколько строк в коде с функциями, начинающимися с «mysql_*» расширения mysql. Вручную отредактируйте код, заменив «mysql_*» на «mysqli_*».

2. Если у вас большой проект или вы очень активно пользовались функциями расширения mysql, вам будет непросто поменять все упоминания устаревших функций. В таком случае вам поможет следующее решение. Создайте PHP-файл, в котором определите функции с именами исключённых, которые будут ссылаться на соответствующие функции расширения mysqli.

Пример кода новой библиотеки. Не надо перечислять все функции расширения, это излишний перфекционизм. Создайте только те, которые встречаются в ваших проектах.

<?
function mysql_connect($server, $username, $password, $new_link = NULL, $client_flags = NULL) {
  $GLOBALS['mysql_oldstyle_link'] = mysqli_connect($server, $username, $password);
  return $GLOBALS['mysql_oldstyle_link'];
 }
function mysql_query($sql) {
  return mysqli_query($GLOBALS['mysql_oldstyle_link'], $sql);
 }
function mysql_fetch_row($res) {
  return mysqli_fetch_row($res);
 }
function mysql_fetch_assoc($res) {
  return mysqli_fetch_assoc($res);
 }
function mysql_fetch_array($res) {
  return mysqli_fetch_array($res);
 }
function mysql_fetch_object($res) {
  return mysqli_fetch_object($res);
 }
function mysql_affected_rows($link = NULL) {
  if ($link===NULL) $link=$GLOBALS['mysql_oldstyle_link'];
  return mysqli_affected_rows($link);
 }
function mysql_insert_id($link = NULL) {
  if ($link===NULL) $link=$GLOBALS['mysql_oldstyle_link'];
  return mysqli_insert_id ($link);
 }
function mysql_select_db($database_name) {
  return mysqli_select_db($GLOBALS['mysql_oldstyle_link'], $database_name);
 }
function mysql_errno($link = NULL) {
  if ($link===NULL) $link=$GLOBALS['mysql_oldstyle_link'];
  return mysqli_errno($link);
 }
function mysql_error($link = NULL) {
  if ($link===NULL) $link=$GLOBALS['mysql_oldstyle_link'];
  return mysqli_error($link);
 }
function mysql_num_rows($res) {
  return mysqli_num_rows($res);
 }
function mysql_free_result($res) {
  return mysqli_free_result($res);
 }
function mysql_close($link) {
  return mysqli_close($link);
 }
function mysql_real_escape_string($sql, $link = NULL) {
  if ($link===NULL) $link=$GLOBALS['mysql_oldstyle_link'];
  return mysqli_real_escape_string($link, $sql);
 }
function mysql_get_server_info($link = NULL) {
  if ($link===NULL) $link=$GLOBALS['mysql_oldstyle_link'];
  return mysqli_get_server_info($link);
 }
 ?>

Данный код сохраните в файл, назовите его, например, deletedmysql.php и сохраните в корне сайта (на одном уровне с index.php главной страницы сайта).

В каждый PHP-файл, в котором встречается ошибка, добавьте строку в самое начало файла, после открывающего кода:

<?
include_once 'deletedmysql.php';
/* далее старый PHP-код */

Совсем идеально будет добавить проверку на версию PHP, так как при переезде на другую площадку или понижении версии PHP до 5.x вы получите ошибку PHP: Fatal error: Cannot redeclare…

if (version_compare(PHP_VERSION, '7.0.0', '>=')) include_once 'deletedmysql.php';

Маленький лайфхак для тех, кому понравился способ 2. Используйте это решение только в качестве временной заглушки. При удобном случае перепрограммируйте код на использование новых функций.


PHP Fatal error: Uncaught Error: Call to undefined function split()

В PHP 7 функция spit() — разбиение строки на массив по регулярному выражению, — была исключена. Альтернатива есть, функции preg_split(), str_split(), explode().

PHP7 Fatal error:  Uncaught Error: Call to undefined function split()

PHP7 Fatal error: Uncaught Error: Call to undefined function split()

В приведённом примере разбить командную строку можно любой функцией. Лично я предпочитаю explode().

Webmasters and website owners often upgrade PHP to the latest version to avoid security vulnerabilities. This sometimes causes compatibility errors, and one such error is “PHP fatal error call to undefined function mysql_connect()”.

As a part of our Server Management Services, we help our customers to fix such PHP errors.

Here, let’s discuss how to fix the PHP fatal error call to undefined function mysql_connect()

What is a PHP fatal error?

Using older versions of PHP may expose the website to security vulnerabilities and more importantly, bugs that are fixed in the recent versions.

So it is a better idea to upgrade the PHP version to the latest one. However, it is also important to prevent PHP fatal errors on your website.

PHP Fatal Errors also known as Critical Errors can occur after the PHP upgrade. This error stops/terminates the execution of scripts.

The mysql_connect() PHP  fatal error may often occur after upgrading your app to PHP 7+. It will try to use “mysql_connect()” functions of php5 in php7. However, mysql_* functions are completely removed from PHP 7+

Also, Fatal error: Uncaught Error: Call to undefined function mysql_connect() error on WordPress site or dashboard looks like,

How to fix the PHP fatal error call to undefined function mysql_connect() error

After upgrading your PHP version to PHP 7+, there is a chance that you will have the following error:

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

This is due to the removal of the mysql_connect function from PHP 7+ versions.

Let’s see how our Support Engineers fixed the PHP fatal errors

1. Upgrade custom code and WordPress plugins or theme

Initially, we’ll identify whether the site is WordPress or using custom code.

If it is WordPress, the main reason could be compatibility issues. The WordPress theme or plugin may not be compatible with higher PHP versions.

So, we will enable the debug option in wp-config.php and find which WordPress plugin or theme is not compatible with PHP 7+. Then, we will recommend them to upgrade/replace the plugin and theme.

If the site is using custom code, then our developer team will help the customers to make the code compatible with the new PHP version.

This solved the issue.

2. Use MySQLi or PDO

Fatal error: Uncaught Error: Call to undefined function mysql_connect() error can be fixed by the use of MySQLi or PDO.

Many customers are using PHP 7.3 version and WordPress latest version. However, they will get the same error after upgrading.

So, we solved the error by enabling the nd_mysqli extension in the PHP configuration and disabling the mysqli one.

How we fix PHP Fatal error: require_once()

Another issue that we commanly dealing with is PHP Fatal error: require_once(): Failed opening required ‘Mail.php’ (include_path=’.:/usr/share/pear:/usr/share/php’)

Recently, one customer had an issue while sending an email by using PHP mail function with SMTP after upgrading PHP from PHP 5.6 to PHP 7+.

On checking, we have found that the error happened due to an incorrect path to Mail.php. He has created the file mail.php instead of Mail.php and specified as require_once(‘Mail.php’)

So we have renamed the file name to Mail.php and solved the error

[Need assistance to fix PHP Fatal errors? – our Support Engineers will help you.]

Conclusion

In short, php fatal error call to undefined function mysql_connect() error occurs after PHP version upgrade. This is due to the removal of the mysql_connect function from PHP 7+ versions. Today, we saw how our Support Engineers fixed the PHP fatal errors.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

PHP 7 является новой версией языка программирования. Её предшественницей считается PHP 5, т. к. 6 версия так и не была выпущена для общего пользования в связи с возникшими во время разработки проблемами. Но это отдельная тема, а сегодня мы разберем, когда при переводе сайта с PHP 5 на PHP 7 возникает ошибка Fatal error: Uncaught Error: Call to undefined function mysql_connect(), и как её исправить, чтобы наш ресурс заработал быстрее, стабильнее и надежнее.

Ошибка Fatal error

Содержание

  1. С чем связана ошибка Fatal error
  2. Создание резервных копий сайта
  3. Настройка журнала ошибок
  4. Переводим сайт на MySQLi
  5. CP1251 и PHP 7 – как расшифровать непонятный набор символов
  6. Заключение

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

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

Текст ошибки Fatal Error

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

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

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

Настройка журнала ошибок

Также настраиваем ведение журнала ошибок (если этого не было сделано ранее). Открываем файл .htaccess и корректируем информацию в нем. Она должна выглядеть следующим образом.

Настройка журнала ошибок

Мы найдем файл .htaccess, если пройдем путь /home/login/domains/domain.ru/public_html/, где login – это логин нашего аккаунта, а domain.ru – домен нашего сайта. Третья строка на картинке выше показывает, где лежит файл с ошибками PHP, которые записываются в процессе работы сайта. Открыть error.log и просмотреть журнал ошибок возможно при помощи файлового менеджера в Панели управления.

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

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

Команды подключения к БД

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

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

Команды MySQLi

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

Запрос сайта

  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. Наша картина выглядит следующим образом.

Скорректированные функции

Теперь сбор и отправка информации из БД должны осуществляться без сбоев.

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

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

Команда php

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

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

Заключение

В этой статье мы рассмотрели, почему при переводе сайта с PHP 5 на PHP 7 возникает ошибка Fatal error: Uncaught Error: Call to undefined function mysql_connect(), и рассмотрели пути ее решения. Сложного в этом ничего нет, были внесены небольшие коррективы в конструкции, отвечающие за подключение к БД и за запросы. Также коснулись ситуации, когда сайт написан с использованием старой кодировки  CP1251. Надеюсь, что предложенные варианты помогут вам исправить ситуацию и без проблем работать на PHP 7.

Понравилась статья? Поделить с друзьями:
  • Php ошибка 500 как вывести
  • Php ошибка 404 не найдено
  • Php ошибка 200 что это
  • Phpmyadmin ошибка конфигурация уже существует настройка отключена
  • Php отобразить ошибки на странице