Ошибка mysql php как модуль

(PHP 4, PHP 5)

mysql_errorВозвращает текст ошибки последней операции с MySQL

Описание

mysql_error(resource $link_identifier = NULL): string

Список параметров

link_identifier

Соединение MySQL. Если идентификатор соединения не был указан,
используется последнее соединение, открытое mysql_connect(). Если такое соединение не было найдено,
функция попытается создать таковое, как если бы mysql_connect() была вызвана без параметров.
Если соединение не было найдено и не смогло быть создано, генерируется ошибка уровня E_WARNING.

Возвращаемые значения

Возвращает текст ошибки выполнения последней функции MySQL,
или '' (пустую строку), если операция
выполнена успешно.

Примеры

Пример #1 Пример использования mysql_error()


<?php
$link
= mysql_connect("localhost", "mysql_user", "mysql_password");mysql_select_db("nonexistentdb", $link);
echo
mysql_errno($link) . ": " . mysql_error($link). "n";mysql_select_db("kossu", $link);
mysql_query("SELECT * FROM nonexistenttable", $link);
echo
mysql_errno($link) . ": " . mysql_error($link) . "n";
?>

Результатом выполнения данного примера
будет что-то подобное:

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

aleczapka _at) gmx dot net

18 years ago


If you want to display errors like "Access denied...", when mysql_error() returns "" and mysql_errno() returns 0, use  $php_errormsg. This Warning will be stored there.  You need to have track_errors set to true in your php.ini.

Note. There is a bug in either documentation about error_reporting() or in mysql_error() function cause manual for mysql_error(), says:  "Errors coming back from the MySQL database backend no longer issue warnings." Which is not true.


Florian Sidler

13 years ago


Be aware that if you are using multiple MySQL connections you MUST support the link identifier to the mysql_error() function. Otherwise your error message will be blank.

Just spent a good 30 minutes trying to figure out why i didn't see my SQL errors.


Pendragon Castle

14 years ago


Using a manipulation of josh ><>'s function, I created the following. It's purpose is to use the DB to store errors. It handles both original query, as well as the error log. Included Larry Ullman's escape_data() as well since I use it in q().

<?php

function escape_data($data){

global
$dbc;

if(
ini_get('magic_quotes_gpc')){

 
$data=stripslashes($data);

}

return
mysql_real_escape_string(trim($data),$dbc);

}

function

q($page,$query){

// $page

$result = mysql_query($query);

if (
mysql_errno()) {

 
$error = "MySQL error ".mysql_errno().": ".mysql_error()."n<br>When executing:<br>n$queryn<br>";

 
$log = mysql_query("INSERT INTO db_errors (error_page,error_text) VALUES ('$page','".escape_data($error)."')");

}

}
// Run the query using q()

$query = "INSERT INTO names (first, last) VALUES ('myfirst', 'mylast'");

$result = q("Sample Page Title",$query);

?>


l dot poot at twing dot nl

16 years ago


When creating large applications it's quite handy to create a custom function for handling queries. Just include this function in every script. And use db_query(in this example) instead of mysql_query.

This example prompts an error in debugmode (variable $b_debugmode ). An e-mail with the error will be sent to the site operator otherwise.

The script writes a log file in directory ( in this case /log ) as well.

The system is vulnerable when database/query information is prompted to visitors. So be sure to hide this information for visitors anytime.

Regars,

Lennart Poot
http://www.twing.nl

<?php
$b_debugmode
= 1; // 0 || 1$system_operator_mail = 'developer@company.com';
$system_from_mail = 'info@mywebsite.com';

function

db_query( $query ){
  global
$b_debugmode;// Perform Query
 
$result = mysql_query($query);// Check result
  // This shows the actual query sent to MySQL, and the error. Useful for debugging.
 
if (!$result) {
    if(
$b_debugmode){
     
$message  = '<b>Invalid query:</b><br>' . mysql_error() . '<br><br>';
     
$message .= '<b>Whole query:</b><br>' . $query . '<br><br>';
      die(
$message);
    }
raise_error('db_query_error: ' . $message);
  }
  return
$result;
}

  function

raise_error( $message ){
    global
$system_operator_mail, $system_from_mail;$serror=
   
"Env:       " . $_SERVER['SERVER_NAME'] . "rn" .
   
"timestamp: " . Date('m/d/Y H:i:s') . "rn" .
   
"script:    " . $_SERVER['PHP_SELF'] . "rn" .
   
"error:     " . $message ."rnrn";// open a log file and write error
   
$fhandle = fopen( '/logs/errors'.date('Ymd').'.txt', 'a' );
    if(
$fhandle){
     
fwrite( $fhandle, $serror );
     
fclose(( $fhandle ));
     }
// e-mail error to system operator
   
if(!$b_debugmode)
     
mail($system_operator_mail, 'error: '.$message, $serror, 'From: ' . $system_from_mail );
  }
?>


Anonymous

18 years ago


My suggested implementation of mysql_error():

$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.n<br />Query: " . $query . "<br />nError: (" . mysql_errno() . ") " . mysql_error());

This will print out something like...

A fatal MySQL error occured.

Query: SELECT * FROM table

Error: (err_no) Bla bla bla, you did everything wrong

It's very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn't let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.

Good luck,

-Scott


olaf at amen-online dot de

18 years ago


When dealing with user input, make sure that you use
<?php
echo htmlspecialchars (mysql_error ());
?>
instead of
<?php
echo mysql_error ();
?>

Otherwise it might be possible to crack into your system by submitting data that causes the SQL query to fail and that also contains javascript commands.

Would it make sense to change the examples in the documentation for mysql_query () and for mysql_error () accordingly?


Anonymous

22 years ago


some error can't handle. Example:

ERROR 1044: Access denied for user: 'ituser@mail.ramon.intranet' to database 'itcom'

This error ocurrs when a intent of a sql insert of no authorized user. The results: mysql_errno = 0 and the mysql_error = "" .


Gianluigi_Zanettini-MegaLab.it

16 years ago


"Errors coming back from the MySQL database backend no longer issue warnings." Please note, you have an error/bug here. In fact, MySQL 5.1 with PHP 5.2:

Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host 'locallllllhost' (11001)

That's a warning, which is not trapped by mysql_error()!


scott at rocketpack dot net

19 years ago


My suggested implementation of mysql_error():

$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.n<br />Query: " . $query . "<br />nError: (" . mysql_errno() . ") " . mysql_error());

This will print out something like...

<b>A fatal MySQL error occured</b>.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong

It's very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn't let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.

Good luck,

-Scott


josh ><>

19 years ago


Oops, the code in my previous post only works for queries that don't return data (INSERT, UPDATE, DELETE, etc.), this updated function should work for all types of queries (using $result = myquery($query);):

    function myquery ($query) {
        $result = mysql_query($query);
        if (mysql_errno())
            echo "MySQL error ".mysql_errno().": ".mysql_error()."n<br>When executing:<br>n$queryn<br>";
        return $result;
    }


phpnet at robzazueta dot com

16 years ago


This is a big one - As of MySQL 4.1 and above, apparently, the way passwords are hashed has changed. PHP 4.x is not compatible with this change, though PHP 5.0 is. I'm still using the 4.x series for various compatibility reasons, so when I set up MySQL 5.0.x on IIS 6.0 running PHP 4.4.4 I was surpised to get this error from mysql_error():

MYSQL: Client does not support authentication protocol requested by server; consider upgrading MySQL client

According to the MySQL site (http://dev.mysql.com/doc/refman/5.0/en/old-client.html) the best fix for this is to use the OLD_PASSWORD() function for your mysql DB user. You can reset it by issuing to MySQL:

Set PASSWORD for 'user'@'host' = OLD_PASSWORD('password');

This saved my hide.


miko_il AT yahoo DOT com

19 years ago

Gianluigi_Zanettini-MegaLab.it

16 years ago


A friend of mine proposed a great solution.

<?php
$old_track
= ini_set('track_errors', '1');

.....

        if (

$this->db_handle!=FALSE && $db_selection_status!=FALSE)
            {
           
$this->connected=1;
           
ini_set('track_errors', $old_track);
            }
        else
            {
           
$this->connected=-1;
           
$mysql_warning=$php_errormsg;
           
ini_set('track_errors', $old_track);
            throw new
mysql_cns_exception(1, $mysql_warning . " " . mysql_error());
            }
?>


Gerrit

8 years ago


The following code returns two times the same error, even though I would have expected only one:

   $ conn = mysql_connect ('localhost', 'root', '');
   $ conn2 = mysql_connect ('localhost', 'root', '');

     mysql_select_db ('db1', $ conn);
   mysql_select_db ('db2', $ conn2);

     $ result = mysql_query ("select 1 from dual", $ conn);
   $ result2 = mysql_query ("select 1 from luad", $ conn2);

     echo mysql_error ($ conn) "<hr>".
   echo mysql_error ($ conn2) "<hr>".

The reason for this is that mysql_connect not working as expected a further connection returns. Since the parameters are equal, a further reference to the previous link is returned. So also changes the second mysql_select_db the selected DB of $conn to 'db2'.

If you change the connection parameters of the second connection to 127.0.0.1, a new connection is returned. In addition to the parameters new_link the mysql_connect() function to be forced.


Одна из распространенных ошибок, возникающих при установке WordPress на новый VPS, заключается в том, что в вашей установке PHP отсутствует ошибка расширения MySQL. Эта ошибка возникает, когда расширение MySQL не существует на VPS. По умолчанию у многих операторов нет этого расширения.

Если вы столкнулись с этой ошибкой во время работы над своим сайтом WordPress, вам не о чем беспокоиться. У этой ошибки много других причин. Многие пользователи WordPress сталкиваются с этой проблемой.

В этой статье мы обсудим 5 простых способов исправить эту ошибку. Выполнив следующие действия, вы можете исправить ошибку «В вашей установке PHP отсутствует расширение MySQL».

В нашей предыдущей статье мы обсуждали, как увеличить память PHP в WordPress.

Как исправить ошибку “Появляется ваша установка PHP…”

Исправьте установку PHP, в которой отсутствует ошибка расширения MySQL

Как упоминалось выше, в этой статье мы представляем 5 методов исправления вашей установки PHP, в которой отсутствует ошибка расширения MySQL.

1. Проверьте и установите расширение PHP MySQL.

По умолчанию расширение PHP MySQL не существует для большинства системных операторов. PHP использует этот модуль для отправки команд SQL и получения их от MySQL.

Чтобы установить расширение PHP MySQL, вам необходимо создать файл info.php.

Для этого вам необходимо скачать Notepad ++ и запустить его. Скопируйте и вставьте приведенный ниже код и сохраните файл как info.php:

Загрузите сохраненный файл в корневой каталог.

Для установки PHP откройте в браузере http://www.yourdomainname.com/info.php.

Перейдите в службу поддержки MySQL. Если у вас установлен MySQL, его версия отображается рядом с версией Client API. Если вы не установили MySQL, выполните следующие действия:

Установите PHP MySQL на серверы, совместимые с RedHat или Ubuntu

В зависимости от вашей версии PHP выполните следующие команды. Помните, что приведенные ниже команды работают, только если ваш сервер совместим с RedHat.

Версия 5:

#yum update
#yum install php-mysql

Версия 7:

#yum update
#yum install php70w-mysql

Запустите Apache или PHP-FPM.

Чтобы исправить вашу установку PHP, похоже, отсутствует ошибка расширения MySQL на серверах Ubuntu, выполните следующие команды. Команды различны для каждой версии PHP:

Версия 5:

#apt-get update
#apt-get install php5-mysqlnd

Версия 7:

#apt-get update
#apt-get install php7.0-mysql

Перезапустите сервер и проверьте, исчезла ли ошибка.

2. Просмотрите конфигурацию каталога расширений MySQL.

Иногда, выполнив шаги, упомянутые выше, вы по-прежнему получаете сообщение о том, что в вашей установке PHP отсутствует ошибка расширения MySQL. Эта ошибка может произойти, если ваш каталог расширений MySQL имеет неправильную конфигурацию. Это происходит, когда вы переносите свой сайт WordPress или используете новый VPS. Чтобы решить эту проблему, вам нужно проверить «extension_dir» в вашем файле PHP.ini.

Откройте файл info.php, созданный на предыдущем шаге. Найдите параметр «Загруженный файл конфигурации» и скопируйте его значение. Например:

Исправьте установку PHP, в которой отсутствует ошибка расширения MySQL

Теперь проверьте раздел «extension_dir». Убедитесь, что расширение PHP не пустое или у него правильный путь. Например:

Исправьте установку PHP, в которой отсутствует ошибка расширения MySQL

Сравните параметры «Загруженный файл конфигурации» и «extension_dir» друг с другом. Если ваше значение «extension_dir» отличается от пути к вашей версии PHP, обязательно исправьте его. Для этого введите правильный путь в вашем файле PHP.ini.

3. Убедитесь, что файлы MySQL.so и MySQL.DLL существуют.

Файл PHP.ini настроен на некоторых веб-сайтах. Этот файл не будет обновляться при обновлении PHP или переносе сервера. С другой стороны, в таких файлах, как PHP.ini, вы можете неправильно написать пути к каталогам расширений.

Лучшее решение этой проблемы – удалить строки ниже или преобразовать их в комментарии в файле PHP.ini:

;extension=mysql.so
;extension_dir=/path/to/extensions/

4. Проверьте пакеты php-mysqlnd-ms на серверах Ubuntu.

В вашей установке PHP отсутствует ошибка расширения MySQL, которая также возникает в новых версиях системного оператора Ubuntu. Потому что Ubuntu использует локальные диски MySQL вместо старой библиотеки PHP. Установка пакета php5-mysqlnd-ms может исправить эту ошибку. Для этого выполните следующую команду:

#apt-get install php5-mysqlnd-ms

Чтобы проверить наличие всех пакетов, содержащих MySQL, выполните следующую команду:

Ubuntu:

Красная шляпа:

5. Проверьте конфигурацию PHP в suPHP_CinfigPath.

Персонализированные файлы PHP загружаются с помощью suPHP_CinfigPath. Однако эта возможность доступна для серверов с включенным suPHP.

Если эти файлы настроены в файле .htaccess, вы можете легко исправить эту ошибку. Эта ошибка возникает из-за ввода значений, которые отличаются от значений расширения MySQL. Особенно на общих серверах, таких как Plesk, cPanel и WHM.

Чтобы исправить эту ошибку, вам необходимо деактивировать suPHP_ConfigPath в файле .htaccess. Если в вашей установке PHP отсутствует ошибка расширения MySQL, вам необходимо проверить файл PHP.ini.

Проверьте значения в PHP.ini и исправьте их.

Вывод

В этой статье мы обсудили, что в вашей установке PHP отсутствует ошибка расширения MySQL.

Мы узнали, что эта ошибка обычно возникает, когда вы обновляете свой PHP или переносите свой сайт на другой сервер. С помощью 5 простых методов мы можем исправить эту ошибку. Мы проверили конфигурацию PHP.ini, чтобы исправить эту ошибку. Кроме того, мы узнали, как проверять разные пакеты в Ubuntu и R

Источник записи: https://betterstudio.com

I have looked through all of the forums that I could find relevant to this question and my problem yet nothing works. I have apache2.2 with php5, phpMyAdmin, and MySQL. I have uncommented the extension, I have checked my phpinfo() and mysqli does not come up. My config directory is where it should be and it still will not load.

Dharman's user avatar

Dharman

30.4k22 gold badges84 silver badges133 bronze badges

asked May 18, 2012 at 4:18

Wesley's user avatar

5

  1. Find out which php.ini is used.
  2. In file php.ini this line:

    extension=mysqli
    
  3. Replace by:

    extension="C:phpextphp_mysqli.dll"
    
  4. Restart apache

Your Common Sense's user avatar

answered Aug 31, 2018 at 21:07

AAGREDA's user avatar

AAGREDAAAGREDA

2312 silver badges2 bronze badges

2

If your configuration files are okay but still having the same issue then install php7.x-mysql according to the version of the installed php.

For example in my case, I’m using php7.3 so I ran the following command to get it all set:

sudo apt install php7.3-mysql

systemctl reload apache2

answered May 20, 2020 at 22:02

faye.babacar78's user avatar

2

I know this is a while ago but I encountered this and followed the other answers here but to no avail, I found the solution via this question (Stackoverflow Question)

Essentially just needed to edit the php.ini file (mine was found at c:xamppphpphp.ini) and uncomment these lines…

;extension=php_mysql.dll
;extension=php_mysqli.dll
;extension=php_pdo_mysql.dll

After restarting apache all was working as expected.

Community's user avatar

answered Jul 1, 2013 at 21:11

sradforth's user avatar

sradforthsradforth

2,1762 gold badges23 silver badges37 bronze badges

  • In your Xampp folder, open php.ini file inside the PHP folder i.e xamppphpphp.ini (with a text editor).

  • Search for extension=mysqli (Ctrl+F), if there are two, look for the one that has been uncommented (without «;» behind)

  • Change the mysqli with the correct path address i.e extension=C:xamppphpextphp_mysqli.dll.

  • On your Xampp control panel, stop and start apache and MySQL

Sonu Sourav's user avatar

Sonu Sourav

2,7962 gold badges12 silver badges25 bronze badges

answered Jun 14, 2020 at 3:00

Adedoyin Adetunji's user avatar

1

sudo apt-get install php7.2-mysql

extension=mysqli.so (add this php.ini file)

sudo service apahce2 restart

Please use above commands to resolve mysqli-extension missing error

answered Apr 27, 2020 at 16:34

Sundar's user avatar

SundarSundar

2532 silver badges6 bronze badges

1

This article can help you Configuring PHP with MySQL for Apache 2 or IIS in Windows. Look at the section «Configure PHP and MySQL under Apache 2», point 3:

extension_dir = "c:phpextensions"      ; FOR PHP 4 ONLY 
extension_dir = "c:phpext"             ; FOR PHP 5 ONLY

You must uncomment extension_dir param line and set it to absolute path to the PHP extensions directory.

answered Jun 4, 2012 at 14:13

Dmytro Zarezenko's user avatar

Dmytro ZarezenkoDmytro Zarezenko

10.5k11 gold badges61 silver badges104 bronze badges

Simply specify the directory in which the loadable extensions (modules) reside in the php.ini file from

; On windows:
extension_dir="C:xamppphpext"

to

; On windows:
;extension_dir = "ext"

Then enable the extension if it was disabled by changing

;extension=mysqli

to

extension=mysqli

answered Dec 4, 2019 at 9:57

SamWanekeya's user avatar

SamWanekeyaSamWanekeya

5465 silver badges10 bronze badges

1

Copy libmysql.dll from the PHP installation folder to the windows folder.

answered May 18, 2013 at 6:28

RM.'s user avatar

RM.RM.

1,97619 silver badges29 bronze badges

I’ve been searching for hours and no one could help me. I did a
simple thing to solve this problem. (WINDOWS 10 x64)

Follow this:

1 — Go to your php_mysqli.dll path (in my case: C:/xampp/php/ext);

2 — Move the php_mysqli.dll to the previous folder (C:/xampp/php);

3 — Open php.ini and search the line: «extension: php_mysqli.dll»;

4 — Change to the path where is your file: extension=»C:xamppphpphp_mysqli.dll»;

5 — Restart your application (wampp, xampp, etc.) and start Apache Server;

The problem was the path ext/php_mysqli.dll, I’ve tried changing the line to extension=»C:xamppphpextphp_mysqli.dll» but doesn’t worked.

answered Sep 1, 2019 at 4:37

Spawn's user avatar

SpawnSpawn

585 bronze badges

0

I had the same problem and I solved it. You can solve it too if you follow these steps:

  1. you have to install PHP to C:/php
    or your current version locate it to this path and specify it as a system variable
  2. then open xampp program and click config and open php.ini
    and uncomment the following lines:

    extension=pdo_mysql
    extension=pdo_mysql
    extension=openssl
    

Dharman's user avatar

Dharman

30.4k22 gold badges84 silver badges133 bronze badges

answered Mar 27, 2020 at 20:54

Mohammed AL MahmoOd's user avatar

try to change PHP version

$sudo update-alternatives --config php

if it didn’t work
change for example from PHP 5.6 => PHP 7.1

    $ sudo a2dismod php5.6
    $ sudo a2enmod php7.1  
    $ sudo service apache2 restart

answered Sep 19, 2022 at 10:55

Hassan Elshazly Eida's user avatar

I encountered this problem today and eventually I realize it was the comment on the line before the mysql dll’s that was causing the problem.

This is what you should have in php.ini by default for PHP 5.5.16:

;extension=php_exif.dll       Must be after mbstring as it depends on it
;extension=php_mysql.dll
;extension=php_mysqli.dll

Besides removing the semi-colons, you also need to delete the line of comment that came after php_exif.dll. This leaves you with

extension=php_exif.dll      
extension=php_mysql.dll
extension=php_mysqli.dll

This solves the problem in my case.

answered Aug 27, 2014 at 5:53

Vinci Chow's user avatar

I simply copied my php_myslqli.dll file from ert folder back to php folder, and it worked for me after restarting my Apache and MySQL from the control Panel

answered Sep 23, 2019 at 14:23

Ocheng Jerome Jesse's user avatar

Its an issue of extension directory. You need to change php extension directory manually to work this.

If you are using AMPP Server, do the following

Goto settings -> PHP -> Configuration

in php7.3.ini Find, (Versions might change)

extension_dir = «» , (Already having some path)

and change value to

extension_dir = «C:Program FilesAmppsphp-7.3ext»

If you are using XAMP

Goto XAMP Settings, Apache -> PHP.ini

Find, extension_dir = in php.ini, and set path of the php extension folder of your local machine. See the below example.

extension_dir = «C:phpext» (Check your path properly)

answered Apr 25, 2020 at 3:47

user3230982's user avatar

In my case, I had a similar issue after full installation of Debian 10.

Commandline:
php -v show I am using php7.4 but print phpinfo() gives me php7.3

Solution: Disable php7.3 Enable php7.4

   $ a2dismod php7.3
    
   $ a2enmod php7.4
    
   $ update-alternatives --set php /usr/bin/php7.4
   $ update-alternatives --set phar /usr/bin/phar7.4
   $ update-alternatives --set phar.phar /usr/bin/phar.phar7.4
   $ update-alternatives --set phpize /usr/bin/phpize7.4
   $ update-alternatives --set php-config /usr/bin/php-config7.4

answered Aug 16, 2020 at 22:39

ShapCyber's user avatar

ShapCyberShapCyber

3,3422 gold badges20 silver badges27 bronze badges

Replace

include_path=C:Program Files (x86)xamppphpPEAR

with following

include_path="C:Program Files (x86)xamppphpPEAR"

i.e Add commas , i checked apache error logs it was showing syntax error so checked whole file for syntax errors.

answered Dec 20, 2020 at 22:36

Waleed Mohsin's user avatar

Waleed MohsinWaleed Mohsin

1,0931 gold badge10 silver badges13 bronze badges

The thing that fixed my problem is: open php.ini then add this extension=php_mysqli.dll

Dharman's user avatar

Dharman

30.4k22 gold badges84 silver badges133 bronze badges

answered Jun 8, 2021 at 8:20

Cyrille Con Morales's user avatar

За последние 24 часа нас посетили 11689 программистов и 714 роботов. Сейчас ищут 304 программиста …

Страница 1 из 2


  1. _Flash_

    _Flash_
    Активный пользователь

    С нами с:
    22 июн 2006
    Сообщения:
    19
    Симпатии:
    0

    Ничего не понимаю.. есть код:и вот такой результат:

    Fatal error: Call to undefined function mysql_connect() in
    C:localhostwwwtesttest.php on line 2

    и че делать? MySQL вроде работает.

  2. php 5 наверное ?
    тогда подключить модуль php_mysql


  3. _Flash_

    _Flash_
    Активный пользователь

    С нами с:
    22 июн 2006
    Сообщения:
    19
    Симпатии:
    0

    ну так он подключен.

    в php.ini extension=php_mysql.dll так ведь?


  4. Mavir

    А phpinfo() показывает информацию о MySQL?

  5. extension_dir прописан верно ? и php работает как модуль апача или cgi (или на iis)?


  6. _Flash_

    _Flash_
    Активный пользователь

    С нами с:
    22 июн 2006
    Сообщения:
    19
    Симпатии:
    0

    Вообщем так.. extension_dir был таким:
    extension_dir=»./»
    сделал таким:
    extesion_dir=»C:/PHP/ext/» — заработало. и в phpinfo() теперь про MySQL появилась информация:
    Active Persistent Links 0
    Active Links 0
    Client API version 4.1.7
    теперь после такого скрипта:

    1.  define (‘MYSQL_HOST’,’127.0.0.1′);
    2.  define (‘MYSQL_PORT’,3306);
    3.  define (‘MYSQL_USER’,’root’);
    4.  define (‘MYSQL_PASS’,»);
    5.  define (‘MYSQL_DB’,’test’);
    6.  $dbusername = MYSQL_USER;
    7.  $dbpassword = MYSQL_PASS;
    8.  $connection = @mysql_connect($dbhost,$dbusername,$dbpassword,»,$dbport) or die(mysql_error());
    9.  $db = mysql_select_db($dbname,$connection) or die(mysql_error());

    пишет:
    Can’t connect to MySQL server on ‘127.0.0.1’ (10061).

    Что теперь?


  7. Hight

    Команда форума
    Модератор


  8. _Flash_

    _Flash_
    Активный пользователь

    С нами с:
    22 июн 2006
    Сообщения:
    19
    Симпатии:
    0

    В службах mysql запущен,
    и mysql клиент консольный пашет.


  9. _Flash_

    _Flash_
    Активный пользователь

    С нами с:
    22 июн 2006
    Сообщения:
    19
    Симпатии:
    0

  10. вместо 127.0.0.1 лучше написать localhost


  11. _Flash_

    _Flash_
    Активный пользователь

    С нами с:
    22 июн 2006
    Сообщения:
    19
    Симпатии:
    0

    Короче. У меня была установлена БД MySQL скаченная в zip архиве, и разархивированная на диск С. Щас я качаю екзешный файл, чтобы не париться.. Просто тогда я думал, что лучше качать архив, как и в PHP.
    Думаю все будет в порядке..


  12. psoi

    psoi
    Активный пользователь

    С нами с:
    25 июн 2006
    Сообщения:
    65
    Симпатии:
    0

    А что делать, если все запущено и настроено, но phpinfo() не выдает инфу по МайЭсКьюЭлю (WinXp SP2+Apache 2.0.x+PHP 5.4.1+MySql 4.x.x)???
    Все extension разкомментированы и extension_dir=C:/php/ext

  13. psoi
    смотреть логи ошибок…


  14. Mavir

    Прописать в переменной окружения PATH путь к файлу libmySQL.dll


  15. _Flash_

    _Flash_
    Активный пользователь

    С нами с:
    22 июн 2006
    Сообщения:
    19
    Симпатии:
    0

    и не забыть перезапустить Apache. Я забыл. .и искал в чем трабла. ))
    Правда мне это не помогло, но зато ошибка изменилась. Вместо undefined function вот это — Warning: mysql_connect() [function.mysql-connect]: Can’t connect to MySQL server on ‘localhost’ (10061) in C:Internetlocalhostwwwtesttest.php on line 2
    Хоть что-то.


  16. Роман

    Роман
    Активный пользователь

    С нами с:
    24 мар 2006
    Сообщения:
    21
    Симпатии:
    0

    1. проверить подключен ли модуль mysql
    2. закинуть libmysql в windows/system32
    3. phpinfo()


  17. Hight

    Команда форума
    Модератор

    phpinfo(); выведи и посмотри подхватил ли пых библиотечку mysql

    php как установлен ??? CGI/FastCGI или как модуль апача ?


  18. 440Hz

    Команда форума
    Модератор

    С нами с:
    21 дек 2012
    Сообщения:
    8.003
    Симпатии:
    1
    Адрес:
    Оттуда

    перестань ставить @ перед вызовом функций и откроешь для себя много нового.


  19. 440Hz

    Команда форума
    Модератор

    С нами с:
    21 дек 2012
    Сообщения:
    8.003
    Симпатии:
    1
    Адрес:
    Оттуда

    как эт пашет? покажи лог работы?


  20. _Flash_

    _Flash_
    Активный пользователь

    С нами с:
    22 июн 2006
    Сообщения:
    19
    Симпатии:
    0

    Ну вот.
    mysql -u root
    showdatabases;
    +———————+
    | Database |
    +———————+
    | information_schema |
    | mysql |
    | test |
    +———————+
    и т. д.


  21. Роман

    Роман
    Активный пользователь

    С нами с:
    24 мар 2006
    Сообщения:
    21
    Симпатии:
    0


  22. AGD_Doctor

    AGD_Doctor
    Активный пользователь

    С нами с:
    3 июл 2006
    Сообщения:
    9
    Симпатии:
    0

    Роман
    Спасибо. С этим порядок.
    Новая трабла:
    include («/main/vars.php»);
    вот эта строчка вызывает следующее:
    Failed opening ‘/main/vars.php’ for inclusion (include_path=’.;C:php4pear’)
    в пхп.ини include_path прописан совсем иной.
    что бы это могло быть?
    И еще я заметил, что не хочет пхп видеть изменения в ини-файле. задал регистер_глобалс с оф на он — не видит.
    где грабли?

Страница 1 из 2

I am doing a tutorial and am getting this error:

Fatal error: Class ‘MySQLi’ not found (LONG URL) on line 8

The code on line 8 is:

$mysqli = new MySQLi($db_server, $db_user, $db_pass, $db_name);

I saw online someone said to see if it was turned on in my phpinfo(), but there wasn’t anything listed in there under for «mysqli».

Also, I am running PHP version 5.2.5

Dharman's user avatar

Dharman

30.4k22 gold badges84 silver badges133 bronze badges

asked Mar 20, 2009 at 16:04

Tylor's user avatar

4

Sounds like you just need to install MySQLi.

If you think you’ve done that and still have a problem, please post your operating system and anything else that might help diagnose it further.

kalehmann's user avatar

kalehmann

4,7416 gold badges24 silver badges36 bronze badges

answered Mar 20, 2009 at 16:07

Greg's user avatar

GregGreg

315k53 gold badges368 silver badges333 bronze badges

5

You can check if the mysqli libraries are present by executing this code:

if (!function_exists('mysqli_init') && !extension_loaded('mysqli')) {
    echo 'We don't have mysqli!!!';
} else {
    echo 'Phew we have it!';
}

answered Mar 21, 2009 at 21:12

karim79's user avatar

karim79karim79

339k67 gold badges413 silver badges406 bronze badges

3

If you are on Ubuntu, run:

 sudo apt-get install php-mysqlnd

And don’t forget to restart the php service after this (Apache or php-fpm depends on the setup).

Your Common Sense's user avatar

answered Mar 20, 2014 at 6:35

anshuman's user avatar

anshumananshuman

3,4881 gold badge19 silver badges13 bronze badges

6

If you’re calling «new mysqli(..)» from within a class that is namespaced, you might see a similar error Fatal error: Class 'foobarmysqli' not found in. The way to fix this is to explicitly set it to the root namespace with a preceding backslash like so:

<?php 
$mysqli = new MySQLi($db_server, $db_user, $db_pass, $db_name);

Dharman's user avatar

Dharman

30.4k22 gold badges84 silver badges133 bronze badges

answered Mar 9, 2015 at 2:06

alexkb's user avatar

alexkbalexkb

3,1462 gold badges29 silver badges29 bronze badges

1

In addition to uncommenting the php_mysqli.dll extension in php.ini, also uncomment the extension_dir directive in php.ini and specify your location:

extension_dir = "C:softwarephpdistext"

This made it work for me.

Sᴀᴍ Onᴇᴌᴀ's user avatar

Sᴀᴍ Onᴇᴌᴀ

8,1808 gold badges34 silver badges58 bronze badges

answered Oct 22, 2010 at 19:16

catawampus's user avatar

catawampuscatawampus

1791 silver badge3 bronze badges

3

If you are on Docker…

Inside php-container RUN:

#docker-php-ext-install mysqli

#apachectl restart

Your Common Sense's user avatar

answered Apr 24, 2020 at 13:22

reyqueson's user avatar

reyquesonreyqueson

4491 gold badge7 silver badges9 bronze badges

0

My OS is Ubuntu. I solved this problem by using:

sudo apt-get install php5-mysql

Peter Mortensen's user avatar

answered Jul 15, 2014 at 2:23

user3839088's user avatar

1

How to Enable mysqli in php.ini

  1. Edit/uncomment by removing ‘;'(colon) the following config in php.ini:
    1st (uncomment and add config):

    include_path = "C:phpincludes"
    

    2nd (uncomment):

    extension_dir = "ext"
    

    3rd (uncomment and edit config):

    extension=C:/PHP/ext/php_mysql.dll
    extension=C:/PHP/ext/php_mysqli.dll
    
  2. Restart the IIS server
  3. Make sure that mysql is running on the system.

How to load php.ini file

  1. Rename any one of the file php.ini-production/php.ini-development to php.ini from C:PHP(note now the extention will be ini i.e «php.ini»).
  2. After renaming to php.ini file restart server
  3. See the changes in http://localhost/phpinfo.php

Dharman's user avatar

Dharman

30.4k22 gold badges84 silver badges133 bronze badges

answered Jun 11, 2018 at 10:59

Gani's user avatar

GaniGani

4121 gold badge7 silver badges16 bronze badges

  1. Open your PHP folder.
  2. Find php.ini-development and open it.
  3. Find ;extension=mysqli
  4. delete the ; symbol
  5. save file and change the file extension from php.ini-development to php.ini
  6. Restart the server and test the code:
    if (!function_exists('mysqli_init') && !extension_loaded('mysqli')) {  
            echo 'We don't have mysqli!!!';  
     } else {  
         echo 'mysqli is installed';
     }
  1. if it not working, change both extension_dir in php.ini from «ext» to «c:phpext»
    and extension=mysqli to extension=php_mysqli.dll then test again
    Remember to reset the server every time you test

Suraj Rao's user avatar

Suraj Rao

29.3k11 gold badges94 silver badges103 bronze badges

answered Nov 11, 2020 at 12:12

Anji's user avatar

AnjiAnji

4692 silver badges9 bronze badges

For anyone using docker, I ran into this issue, and resolved it by using my own Dockerfile instead of the php:fpm image:

FROM php:fpm

RUN docker-php-ext-install mysqli

answered Apr 17, 2020 at 19:09

bozdoz's user avatar

bozdozbozdoz

12.4k7 gold badges66 silver badges95 bronze badges

Seems like problem with your installation.

  • Have you installed MySQLi?
  • Have you activated it in php.ini?
  • Restarted Apache and/or PHP-FPM?

http://www.php.net/manual/en/mysqli.installation.php

mario's user avatar

mario

144k20 gold badges237 silver badges291 bronze badges

answered Mar 20, 2009 at 16:08

vartec's user avatar

vartecvartec

131k36 gold badges217 silver badges244 bronze badges

The PHP zip includes most of the commonly used extensions (*.dll on windows such as php_mysqli.dll) under the ext directory, however they are not enabled by default. You might be getting this Fatal Error when trying to use MySQLi:

( ! ) Fatal error: Uncaught Error: Class 'mysqli' not found in C:myProject class.Database.php on line 24

To enable extensions, open php.ini (you might need to first copy php.ini-development as php.ini), and un-comment (or add) these two lines:

extension_dir = "ext"

And any particular extensions you are getting Fatal Errors for, i.e. for mysqli:

extension=mysqli

answered Mar 12, 2018 at 2:26

Griknok's user avatar

GriknokGriknok

3842 silver badges13 bronze badges

On a fresh install of PHP, remove ; before extension_dir in php.ini.

answered Mar 23, 2019 at 0:52

Andrei's user avatar

AndreiAndrei

1612 silver badges13 bronze badges

I thought I might help anybody with the same problem using Namesco servers.
I have been trying to fix this problem after moving a database from my local server on home pc to namesco. They would not assist they said it was a coding issue.

  • However, it was simple to fix from their CPANEl LINUX hosting
    interface.
  • Click on php.
  • then click on php modules and from their list of preinstalled modules just click the box for mysqli.
  • Then click save. (No need to change code if it worked(s) on another server.)

Unfortunately, their support articles were a waste of time. After reading this I went to admin interface with a new determination.

Dharman's user avatar

Dharman

30.4k22 gold badges84 silver badges133 bronze badges

answered Oct 25, 2017 at 15:51

John's user avatar

Some distributions (such as Gentoo) support multiple installations of PHP, and you have to make sure you’re using one with mysqli installed and enabled.

On Gentoo, I had installed a new PHP (with the mysqli USE flag enabled), but I needed to activate the new version of PHP (since the old one must have been missing mysqli):

# eselect php list apache2
  [1]   php5.3 *
  [2]   php5.5
# eselect php set apache2 2
You have to run `/etc/init.d/apache2 restart' for the changes to take effect
# /etc/init.d/apache2 restart

Peter Mortensen's user avatar

answered Nov 16, 2013 at 1:55

Jared Thirsk's user avatar

Jared ThirskJared Thirsk

1,20717 silver badges16 bronze badges

I checked all above and it didn’t work for me,

There are some steps I found.

I used PHP Version 5.5.9-1ubuntu4.17 on Ubuntu 14.04

First check the folder

#ls /etc/php5/mods-available/
json.ini  mcrypt.ini  mysqli.ini  mysql.ini  mysqlnd.ini  opcache.ini  pdo.ini  pdo_mysql.ini  readline.ini  xcache.ini

If it did not contain mysqli.ini, read other answer for installing it,

Open php.ini find extension_dir

In my case , I must set extension_dir = /usr/lib/php5/20121212

And restart apache2 : /ect/init.d/apache2 restart

answered Jul 18, 2016 at 8:03

vanduc1102's user avatar

vanduc1102vanduc1102

5,6401 gold badge45 silver badges42 bronze badges

on ubuntu:

sudo apt-get install php-mysql
sudo service apache2 restart

answered Jul 25, 2018 at 17:40

vishalknishad's user avatar

on Debian 10

apt install php-mysql

/etc/init.d/apache2 restart

answered Jan 2, 2020 at 20:44

Salvador Rueda's user avatar

Salvador RuedaSalvador Rueda

8152 gold badges7 silver badges15 bronze badges

I found a solution for this problem after a long analysing procedure.
After properly testing my php installation with the command line features I found out that the php is working well and could work with the mysql database. Btw. you can run code-files with php code with the command php -f filename.php
So I realized, it must something be wrong with the Apache.
I made a file with just the phpinfo() function inside.
Here I saw, that in the line
Loaded Configuration File
my config file was not loaded, instead there was mentioned (none).

Finally I found within the Apache configuration the entry

<IfModule php5_module>
    PHPINIDir "C:/xampp/php"
</IfModule>

But I’ve installed the PHP 7 and so the Apache could not load the php.ini file because there was no entry for that.
I added

<IfModule php7_module>
    PHPINIDir "C:/xampp/php"
</IfModule>

and after restart Apache all works well.

These code blocks above I found in my httpd-xampp.conf file. May it is somewhere else at your configuration.
In the same file I had changed before the settings for the php 7 as replacement for the php 5 version.

#
# PHP-Module setup
#
#LoadFile "C:/xampp/php/php5ts.dll"
#LoadModule php5_module "C:/xampp/php/php5apache2_4.dll"
LoadFile "C:/xampp/php/php7ts.dll"
LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"

As you can see I have the xampp package installed but this problem was just on the Apache side.

Dharman's user avatar

Dharman

30.4k22 gold badges84 silver badges133 bronze badges

answered Nov 1, 2018 at 19:58

Klaus-Peter Ow Lex's user avatar

install
phpXX-extension by PHP.
In my FreeBSD’s case:

pkg install php74-extensions

Dharman's user avatar

Dharman

30.4k22 gold badges84 silver badges133 bronze badges

answered Jul 20, 2020 at 19:23

Biddut Mitra's user avatar

I’m using xampp and my problem was fixed once i rename:

extension_dir = "ext"

to

extension_dir = "C:xamppphpext"

PS: Don’t forget to restart apache after making this change!

answered Sep 12, 2020 at 2:27

Andrei's user avatar

AndreiAndrei

1612 silver badges13 bronze badges

In php.ini :

extension_dir ="c:/wamp64/bin/php/php7.4.9/ext/"

Make sure the PHP version is correct.

Obsidian's user avatar

Obsidian

3,5518 gold badges17 silver badges30 bronze badges

answered Sep 22, 2020 at 15:19

Papa Mike's user avatar

All you have to do is go to the php.ini file and on line 926 (depending on version) delete #. It should look like this:

;extension=ldap
;extension=mbstring
;extension=exif
extension=mysqli
;extension=oci8_12c
;extension=odbc

Save the file and open console (cmd) as administrator. Go to the path Apache24 / bin and enter httpd -k restart. This command will restart your server. After that, refresh the page and everything should work.

answered Apr 14, 2021 at 8:58

olios's user avatar

oliosolios

596 bronze badges

When I tried my PHP web app it was giving me the same error.

By googling I found out the MySQL plugin for the PHP server was missing with my installation. I am using Ubuntu, so when I tried MySQL plugin for PHP I found out 2 are there,

php-mysql and php<version>-mysql

I issued command — php --version in my terminal, I was having php7.4,

again I issued apt install php7.4-mysql

It worked.

answered Jul 9, 2021 at 3:35

Willey Hute's user avatar

Willey HuteWilley Hute

94213 silver badges18 bronze badges

This issue can be also caused by the .htaccess file misconfiguration.

answered Sep 2, 2021 at 10:01

16851556's user avatar

1685155616851556

2393 silver badges11 bronze badges

If you tried all answers above and are still out of luck, then do check if the version numbers of the packages installed on your system really match:

apache2-mod_php7-7.4.33-150200.3.46.2.x86_64
php7-mysql-7.4.33-150200.3.46.2.x86_64

Once I had to do a manual installation from a different repo, which lead to certain libs not getting loaded (though their config was OK and their .ini files were getting parsed).

You can also try using

php -S <server_ip>:8080

to launch a test server and see if your missing module (mysqli) loads there. If it shows up in phpinfo there (and doesn’t in your regular configuration), then you at least know where to have a look at…

answered Apr 15 at 10:28

Helge Telefonmann's user avatar

Понравилась статья? Поделить с друзьями:
  • Ошибка mysql no such file or directory
  • Ошибка mysql invalid default value for
  • Ошибка mysql host is not allowed
  • Ошибка mysql error the error returned was
  • Ошибка mysql duplicate entry 1 for key primary