Ошибка в mysqli class php

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 badges25 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,1562 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

4842 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

8352 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,5618 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

AlexKOR5

50 / 14 / 3

Регистрация: 15.02.2019

Сообщений: 514

1

17.05.2021, 09:48. Показов 12260. Ответов 8

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте, IDE PhpStorm выдает мне ошибку:

Код

Fatal error: Uncaught Error: Class "mysqli" not found in E:ProgramsOpen ServerOSPaneldomainsappfunction.php:4
Stack trace:
#0 E:ProgramsOpen ServerOSPaneldomainsappregions.php(2): require_once()
#1 {main}
  thrown in E:ProgramsOpen ServerOSPaneldomainsappfunction.php on line 4

когда я подключил файл «function.php» в другой файл и воспользовался запросом до базы.

function.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
include_once 'login.php';
global $dbhost, $dbuser, $dbpass, $dbname;
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
 
if (!$conn->connect_error) {
} else {
    $system_error_message = $conn->connect_error;
    $user_error_message = "Connect Error!";
    handle_error($user_error_message, $system_error_message);
}
function handle_error($user_error_message, $system_error_message)
{
    header("Location: show_error.php?" . "error_message={$user_error_message}&" . "system_error_message={$system_error_message}");
    exit();
}

login.php

PHP
1
2
3
4
5
<?php
$dbhost = 'localhost';
$dbuser = 'kor';
$dbpass = '1111';
$dbname = 'course';

ошибка при подключении в этом файле
regions.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
require_once 'function.php';
global $conn;
 
if (!isset($_REQUEST['countries_id'])) {
    handle_error("Не вказане зображення для завантаження", "Не вказане зображення для завантаження");
}
$countries_id = $_REQUEST['countries_id'];
 
$query = sprintf("SELECT * FROM regions WHERE countries_id = %d", $countries_id);
$res = $conn->query($query);
($res) or handle_error("Трапився збій при отриманні інформації про країни від бази даних", $conn->connect_error);
//echo 'ok';
//......................................................................

Как устранить эту ошибку?



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

17.05.2021, 09:48

Ответы с готовыми решениями:

Робот может перемещаться в четырех направлениях («С» — север, «З» — запад, «Ю» — юг, «В» — восток) и принимать
Робот может перемещаться в четырех направлениях (&quot;С&quot; — север, &quot;З&quot; — запад, &quot;Ю&quot; — юг, &quot;В&quot; -…

Тысячные числа исправлять к примеру с «1200» на «1 200», «12000» на «12 000» и т.д
Собственно числа исправлять к примеру с &quot;1200&quot; на &quot;1 200&quot;, &quot;12000&quot; на &quot;12 000&quot;, &quot;120000&quot; на…

Как поменять кнопку «выбрать файл» в форме обратной связи (class.phpmailer.php)?
Уважаемые программисты, добрый вечер!
Помогите, пож-ста, справиться с такой задачкой.
Есть форма…

Составить программу, которая в строке s заменяет все вхождения » ph » на » f » а все вхождений » ed » на » ing
Составить программу, которая в строке s заменяет все вхождения &quot; ph &quot; на &quot; f &quot; а все вхождений &quot; ed…

8

1982 / 1206 / 440

Регистрация: 13.06.2013

Сообщений: 4,096

17.05.2021, 11:19

2

Включить mysql в настройках open server.



1



50 / 14 / 3

Регистрация: 15.02.2019

Сообщений: 514

17.05.2021, 12:17

 [ТС]

3

Цитата
Сообщение от tarasalk
Посмотреть сообщение

Включить mysql в настройках open server.

Проблема в том что база данных была создана в MariaDB 10.3



0



50 / 14 / 3

Регистрация: 15.02.2019

Сообщений: 514

20.05.2021, 18:05

 [ТС]

4

Цитата
Сообщение от tarasalk
Посмотреть сообщение

Включить mysql в настройках open server.

Базу данных перенес на MySQL 8 и настройки изменил, но ошибка осталась.
Что делать?

Миниатюры

Как устранить ошибку " Class "mysqli" not found in function.php"?
 



0



Эксперт PHP

4845 / 3857 / 1599

Регистрация: 24.04.2014

Сообщений: 11,317

20.05.2021, 18:10

5

Цитата
Сообщение от AlexKOR5
Посмотреть сообщение

Проблема в том что база данных была создана в MariaDB 10.3

Нет, проблема в том что не установлено расширение mysqli для php, а не в mariadb вместо mysql.



1



50 / 14 / 3

Регистрация: 15.02.2019

Сообщений: 514

20.05.2021, 18:52

 [ТС]

6

Цитата
Сообщение от Jewbacabra
Посмотреть сообщение

Нет, проблема в том что не установлено расширение mysqli для php, а не в mariadb вместо mysql.

Спасибо за отклик!
Как же это установить?
О том как установить смотрел в интернете, но так и не нашел хорошего и рабочего ответа.



0



1982 / 1206 / 440

Регистрация: 13.06.2013

Сообщений: 4,096

20.05.2021, 19:26

7

Возможно там по дефолту mysqli не включен, только PDO.
Поищите в php.ini подобную строчку ;extension=php_mysqli.dll, нужно убрать ‘;’, сохранить и перезагрузить сервер.



1



1238 / 938 / 222

Регистрация: 01.10.2018

Сообщений: 3,646

20.05.2021, 19:34

8

Раскомментируйте соответствующую строку в php.ini и перезапустите Web-сервер. Закомментированная строка может выглядеть так: ;extension=php_mysqli.dll или ;extension=mysqli.

Добавлено через 2 минуты

Цитата
Сообщение от tarasalk
Посмотреть сообщение

Возможно там по дефолту mysqli не включен, только PDO.

Возможно, и PDO не включен



1



ft4l

Невнимательный

2380 / 742 / 265

Регистрация: 08.02.2013

Сообщений: 5,045

Записей в блоге: 2

20.05.2021, 19:56

9

Цитата
Сообщение от AlexKOR5
Посмотреть сообщение

» Class «mysqli» not found in function.php»

Бывает ещё из-за пространств имён такое

PHP
1
2
3
4
5
6
7
<?php
namespace my;
header('Content-type: text/plain; charset=utf-8');
 
$conn = new mysqli(NULL, 'root', '', 'test');
var_export($conn);
exit;

надо делать new mysqli
… но текст ошибки

отличается

<b>Fatal error</b>: Class ‘mymysqli’ not found in ….

Цитата
Сообщение от AlexKOR5
Посмотреть сообщение

как установить

включить просто в php.ini … если не включено

… если ось виндовс
extension=php_mysqli.dll
… и php выполняется модулем apache
файл с именем php.ini , если в httpd.conf присутствует PHPINIDir /xxxxxx ,
ищет в этой /xxxxxx
… или ищет c:windowsphp.ini

Как php выполняется из «IDE PhpStorm» я даже не интересовался



0



Выдает эту ошибку: Fatal error: Uncaught Error: Class «mysqli» not found.

Код:

<?php
$mysqli = new mysqli("localhost", "root", "", "mybase");

$mysqli->query("SET NAMES 'utf8'");
$success = $mysqli->query("INSERT INTO `users`
(`login`, `password`, `reg-date`)
VALUES ('123', '" . md5("123") . "', '" . time() . "')");
echo $success;

$mysqli->close();
// echo phpinfo();

Заранее спасибо. Прошу прощения если вопрос глупый и ответ очевидный.

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


  1. nrdgrauf

    С нами с:
    14 май 2016
    Сообщения:
    3
    Симпатии:
    0

    Здравствуйте. Использую операционную систему Arch Linux, установил MySQL, PHP7 и хотел подключиться к моей базе данных локально, так как показано тут => https://php.ru/manual/mysqli.construct.html
    Написал файл connect.php:

    1. $mysqli = new mysqli(‘localhost’, ‘root’, ‘my_password’);
    2. if ($mysqli->connect_error) {
    3.     die («<p>Error. Cannot connect to database: « . $mysqli->connect_error . «</p>»);
    4. echo «<p>Connected to MySQL!</p>»;

    Запустил встроенный в PHP сервер и попробовал обратиться к connect.php, но получил такую ошибку:

    1. /connect.php — Uncaught Error: Class ‘mysqli’ not found in /home/nrdgrauf/Desktop/php/test1/connect.php:2
    2.   thrown in /home/nrdgrauf/Desktop/php/test1/connect.php on line 2

    Никогда раньше не имел дела с PHP, но решил поучиться. Помогите пожалуйста.


  2. denis01

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

    Расширение mysqli установлено? Оно включено в php.ini?


  3. nrdgrauf

    С нами с:
    14 май 2016
    Сообщения:
    3
    Симпатии:
    0

    Я не знаю. Я что-то примерно это же находил в интернете, но не нашел php.ini. Как его установить и где найти php.ini (я сделал поиск по /, его нигде нет).


  4. denis01

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

    вызови функцию phpinfo(); там будет написано где лежит php.ini.
    тут нужны навыки использования linux, обычно файлы конфигурации хранятся в папке /etc и там обычно есть папка php с файлом php.ini


  5. nrdgrauf

    С нами с:
    14 май 2016
    Сообщения:
    3
    Симпатии:
    0

    Нашел этот файл, дальше что?


  6. denis01

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

    найди в нём ;extension=php_mysqli или что-то подобное и посмотри нет ли знака ; перед ним, это значит что отключён.


  7. mr.akv

    mr.akv
    Активный пользователь

    С нами с:
    31 мар 2015
    Сообщения:
    1.604
    Симпатии:
    206

mysqli_error

(PHP 5, PHP 7, PHP 8)

mysqli::$errormysqli_errorReturns a string description of the last error

Description

Object-oriented style

Procedural style

mysqli_error(mysqli $mysql): string

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example #1 $mysqli->error example

Object-oriented style


<?php
$mysqli
= new mysqli("localhost", "my_user", "my_password", "world");/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %sn", $mysqli->connect_error);
exit();
}

if (!

$mysqli->query("SET a=1")) {
printf("Error message: %sn", $mysqli->error);
}
/* close connection */
$mysqli->close();
?>

Procedural style


<?php
$link
= mysqli_connect("localhost", "my_user", "my_password", "world");/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %sn", mysqli_connect_error());
exit();
}

if (!

mysqli_query($link, "SET a=1")) {
printf("Error message: %sn", mysqli_error($link));
}
/* close connection */
mysqli_close($link);
?>

The above examples will output:

Error message: Unknown system variable 'a'

See Also

  • mysqli_connect_errno() — Returns the error code from last connect call
  • mysqli_connect_error() — Returns a description of the last connection error
  • mysqli_errno() — Returns the error code for the most recent function call
  • mysqli_sqlstate() — Returns the SQLSTATE error from previous MySQL operation

information at saunderswebsolutions dot com

17 years ago


The mysqli_sql_exception class is not available to PHP 5.05

I used this code to catch errors
<?php
$query
= "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (!

$res) {
  
printf("Errormessage: %sn", $mysqli->error);
}
?>
The problem with this is that valid values for $res are: a mysqli_result object , true or false
This doesn't tell us that there has been an error with the sql used.
If you pass an update statement, false is a valid result if the update fails.

So, a better way is:
<?php
$query
= "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (!

$mysqli->error) {
  
printf("Errormessage: %sn", $mysqli->error);
}
?>

This would output something like:
Unexpected PHP error [mysqli::query() [<a href='function.query'>function.query</a>]: (42S22/1054): Unknown column 'XXname' in 'field list'] severity [E_WARNING] in [G:database.php] line [249]

Very frustrating as I wanted to also catch the sql error and print out the stack trace.

A better way is:

<?php
mysqli_report
(MYSQLI_REPORT_OFF); //Turn off irritating default messages$mysqli = new mysqli("localhost", "my_user", "my_password", "world");$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (

$mysqli->error) {
    try {   
        throw new
Exception("MySQL error $mysqli->error <br> Query:<br> $query", $msqli->errno);   
    } catch(
Exception $e ) {
        echo
"Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >";
        echo
nl2br($e->getTraceAsString());
    }
}
//Do stuff with the result
?>
Prints out something like:
Error No: 1054
Unknown column 'XXname' in 'field list'
Query:
SELECT XXname FROM customer_table

#0 G:\database.php(251): database->dbError('Unknown column ...', 1054, 'getQuery()', 'SELECT XXname F...')
#1 G:dataWorkSites1framework5testsdbtest.php(29): database->getString('SELECT XXname F...')
#2 c:PHPincludessimpletestrunner.php(58): testOfDB->testGetVal()
#3 c:PHPincludessimpletestrunner.php(96): SimpleInvoker->invoke('testGetVal')
#4 c:PHPincludessimpletestrunner.php(125): SimpleInvokerDecorator->invoke('testGetVal')
#5 c:PHPincludessimpletestrunner.php(183): SimpleErrorTrappingInvoker->invoke('testGetVal')
#6 c:PHPincludessimpletestsimple_test.php(90): SimpleRunner->run()
#7 c:PHPincludessimpletestsimple_test.php(498): SimpleTestCase->run(Object(HtmlReporter))
#8 c:PHPincludessimpletestsimple_test.php(500): GroupTest->run(Object(HtmlReporter))
#9 G:all_tests.php(16): GroupTest->run(Object(HtmlReporter))

This will actually print out the error, a stack trace and the offending sql statement. Much more helpful when the sql statement is generated somewhere else in the code.


se (at) brainbits (dot) net

17 years ago


The decription "mysqli_error -- Returns a string description of the LAST error" is not exactly that what you get from mysqli_error. You get the error description from the last mysqli-function, not from the last mysql-error.

If you have the following situation

if (!$mysqli->query("SET a=1")) {
   $mysqli->query("ROLLBACK;")
   printf("Errormessage: %sn", $mysqli->error);
}

you don't get an error-message, if the ROLLBACK-Query didn't failed, too. In order to get the right error-message you have to write:

if (!$mysqli->query("SET a=1")) {
   printf("Errormessage: %sn", $mysqli->error);
   $mysqli->query("ROLLBACK;")
}


callforeach at gmail dot com

8 years ago


I had to set mysqli_report(MYSQLI_REPORT_ALL) at the begin of my script to be able to catch mysqli errors within the catch block of my php code.

Initially, I used the below code to throw and subsequent catch mysqli exceptions

<?php
try {
  
$mysqli = new mysqli('localhost','root','pwd','db');
    if (
$mysqli->connect_errno)
        throw new
Exception($mysqli->connect_error);

} catch (

Exception $e) {
     echo
$e->getMessage();
}
I realized the exception was being thrown before the actual throw statement and hence the catch block was not being called.My current code looks like
mysqli_report
(MYSQLI_REPORT_ALL) ;
try {
     
$mysqli = new mysqli('localhost','root','pwd','db');
     
/* I don't need to throw the exception, it's being thrown automatically */} catch (Exception $e) {
  echo
$e->getMessage();
}
This works fine and I'm able to trap all mysqli errors


asmith16 at littlesvr dot ca

9 years ago


Please note that the string returned may contain data initially provided by the user, possibly making your code vulnerable to XSS.

So even if you escape everything in your SQL query using mysqli_real_escape_string(), make sure that if you plan to display the string returned by mysqli_error() you run that string through htmlspecialchars().

As far as I can tell the two escape functions don't escape the same characters, which is why you need both (the first for SQL and the second for HTML/JS).


abderrahmanekaddour dot aissat at gmail dot com

9 months ago


<?php// The idea is the add formated errors information for developers to easier bugs detection.$myfile = fopen("database_log.log", "r");
$db = new mysqli("localhost", "root","root","data");
if(!
$db->query("SELECT")){
 
$timestamp = new DateTime();
 
$data_err = " {
     "title": " Select statement error ",
     "date_time": "
.$timestamp->getTimestamp().",
     "error":" "
.$db->error." "
     } "
; // Do more information
 
fwrite($myfile, $data_err); // writing data
}
   
// In separate file do file read and format it for good visual.$db->close(); 
fclose($myfile);
?>

information at saunderswebsolutions dot com

17 years ago


Hi, you can also use the new mysqli_sql_exception to catch sql errors.
Example:
<?php
//set up $mysqli_instance here..
$Select = "SELECT xyz FROM mytable ";
try {
   
$res = $mysqli_instance->query($Select);
}catch (
mysqli_sql_exception $e) {
    print
"Error Code <br>".$e->getCode();
    print
"Error Message <br>".$e->getMessage();
    print
"Strack Trace <br>".nl2br($e->getTraceAsString());
}
?>
Will print out something like
Error Code: 0
Error Message
No index used in query/prepared statement select sess_value from frame_sessions where sess_name = '5b85upjqkitjsostvs6g9rkul1'
Strack Trace:
#0 G:classfileslib5database.php(214): mysqli->query('select sess_val...')
#1 G:classfileslib5Session.php(52): database->getString('select sess_val...')
#2 [internal function]: sess_read('5b85upjqkitjsos...')
#3 G:classfilesincludes.php(50): session_start()
#4 G:testsall_tests.php(4): include('G:dataWorkSit...')
#5 {main}

Anonymous

3 years ago


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
                $this->connection = mysqli_connect($hostname,$username,$password, $dbname);
} catch (Exception $e) {
                echo "Errno: " . mysqli_connect_errno() . PHP_EOL;
                echo "Text error: " . mysqli_connect_error() . PHP_EOL;
                exit;
}

Понравилась статья? Поделить с друзьями:
  • Ошибка в league of legends you are
  • Ошибка в multi theft auto
  • Ошибка в qr коде вакцинированного
  • Ошибка в kernel в линуксе
  • Ошибка в mta province cl10