Вот собственно текст ошибки:
Warning: mysqli_connect(): (HY000/2002): Unknown error while connecting in /var/www/somesite/db.php on line 2
Подключение идёт на удаленный сервер.
Если подключаться на локалку то все работает.
Ошибка при подключении к бд mysql из php
i_love_linux, Ну ок, а что в файле /var/www/somesite/db.php ??
DiabloPC, код для подключения к бд :D
$db = mysqli_connect('remote_ip', 'user', 'pass', 'dbname') or die("Ошибка подключения к базе данных");
Если подключаться через консоль mysql -h remote_ip -u user -p, то все нормально работает.
Из языка python подключение тоже нормально происходит.
Видимо ошибка именно в php.
Кстати, версия php7 стоит.
i_love_linux, даже PHP5 поддерживает конструкцию вида:
$db = new mysqli('host', 'user', 'pass', 'base');
if (!$db) {
exit("Пишем сообщение об ошибке");
}Почему не использовать такой вариант? А для запроса:
$res = $db->query("query text");P.S. Функции die() и exit() - синонимы.
Rizado, просто я привык к процедурному стилю.
Собственно это не важно.
Ни процедурный стиль, ни ООП не работает.
Та же ошибка.
Вообще бред какой то с этим mysql'ом.
Ниразу не сталкивался с "неизвестной ошибкой"
Видимо и не я один, даже гугл молчит по этому поводу.
А если так?
$connection = mysqli_connect( 'host', 'username', 'password', 'database', 'port', 'socket');
Или через PDO попробуй.
i_love_linux, идиотский вопрос - а что насчёт прав доступа к БД? Не забываем, что нужно указывать не только пользователя, но и с каких IP он может подключаться.
Вряд ли скрипт и команда из консоли с одного компьютера выполнялись...
Ну и если менялись права доступа, не забываем выполнить на MySQL-сервере [console=inline]flush privileges[/console].
i2ks, неа, тоже не работает((
PDO также выдает Unknown error :(
Rizado
С правами доступа все норм.
Айпишник добавил в список разрешенных.
И скрипт и команда в консоли выпонялись на одном компьютере.
И python скрипт тоже.
i_love_linux, в таком случае настоятельно рекомендую выложить файл, только не светить имя пользователя и пароль. Замените их звёздочками.
кстати, а extension с mysqli то прописан? :-)
i2ks, для Apache? Тоже вариант. Хотя сейчас сложно найти, где это не прописано :) .
Да хз что там, я уже apache давно не использовал, везде nginx+fpm :-)i2ks, для Apache? Тоже вариант. Хотя сейчас сложно найти, где это не прописано .
Rizado, Вот содержимое файла.
<?php
$db = mysqli_connect('remote_server', 'user', 'pass', 'dbname') or die("Ошибка подключения к базе данных");
mysqli_set_charset($db, 'utf8');
Данные естественно заменил :)
i_love_linux, это всё? То есть, никакой полезной работы файл не выполняет? Выложите весь код на Pastebin.
Кстати, рекомендация.
1. Подключите файл конфигурации, чтобы при смене имени/пароля править только в одном месте (ну и не думать об удалении личных данных, если просите помощь). Хотя бы так:
<?php
require_once __DIR__ . "/config.php";
$db = new mysqli($db_host, $db_user, $db_pass, $db_name);
$db->query("SET NAMES UTF8");И файл конфигурации:
<?php
$db_host = 'my_remote_host';
$db_user = 'username';
$db_pass = 'userpass';
$db_name = 'database';2. [console=inline]SET NAMES[/console] работает как минимум не хуже (в первом фрагменте кода).
i2ks, да, прописано. Запросы к локалке идут нормально.
Rizado, почему не выполняет?
В этом файле происходит подключение к бд.
Я его потом инклудю куда мне нужно и все.
Честно говоря не понял, зачем мне создавать отделный файл для того чтобы там хранить данные для подключения??
Если у меня и так само подключение(с прописанными данными) хранится в отдельном файле.
Сейчас обнаружил одну интересную вещь.
Если к локалке подключаться через ip 127.0.0.1, а не через домен localhost, то выдает ту же ошибку.
Выходит оно с айпишниками в качестве хоста не хочет работать.
Выходит оно с айпишниками в качестве хоста не хочет работать.
Выходит, смотреть надо, что там в httpd.conf и .htaccess
Что то у вас не так там, сейчас поставил mysql + php7.0 , и корректно подключился.
вот лог:
170421 12:09:17 36 Connect userdb@192.168.1.208 on dbtest
36 Query SET NAMES utf8
36 Quit
[quote="i_love_linux"]Выходит оно с айпишниками в качестве хоста не хочет работать.
Выходит, смотреть надо, что там в httpd.conf и .htaccess[/quote]
.htaccess нету.
Вот содержимое httpd.conf (у меня он называется apache2.conf)
Показать
# This is the main Apache server configuration file. It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.
# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
# /etc/apache2/
# |-- apache2.conf
# | `-- ports.conf
# |-- mods-enabled
# | |-- *.load
# | `-- *.conf
# |-- conf-enabled
# | `-- *.conf
# `-- sites-enabled
# `-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
# together by including all remaining configuration files when starting up the
# web server.
#
# * ports.conf is always included from the main configuration file. It is
# supposed to determine listening ports for incoming connections which can be
# customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
# directories contain particular configuration snippets which manage modules,
# global configuration fragments, or virtual host configurations,
# respectively.
#
# They are activated by symlinking available configuration files from their
# respective *-available/ counterparts. These should be managed by using our
# helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
# their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
# the default configuration, apache2 needs to be started/stopped with
# /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
# work with the default configuration.
# Global configuration
#
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE! If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"
#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
Mutex file:${APACHE_LOCK_DIR} default
#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}
#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300
#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On
#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100
#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5
# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log
#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn
# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf
# Include list of ports to listen on
Include ports.conf
# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
Options FollowSymLinks
AllowOverride None
Require all denied
</Directory>
<Directory /usr/share>
AllowOverride None
Require all granted
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
#<Directory /srv/>
# Options Indexes FollowSymLinks
# AllowOverride None
# Require all granted
#</Directory>
# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives. See also the AllowOverride
# directive.
#
AccessFileName .htaccess
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^\.ht">
Require all denied
</FilesMatch>
#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.
# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf
# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
i2ks, Да, я знаю! У меня на компьютере тоже все прекрасно работает.
Проблема наблюдается на дистре который развернут на андроид смартфоне в chroot окружении и имеет архитектутру armhf.
Вот лог mysql:
Показать
2017-04-21T13:54:55.045519Z mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
2017-04-21T13:54:55.083241Z 0 [Warning] Changed limits: max_open_files: 1024 (requested 5000)
2017-04-21T13:54:55.083770Z 0 [Warning] Changed limits: table_open_cache: 431 (requested 2000)
2017-04-21T13:54:55.343032Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-04-21T13:54:55.344589Z 0 [Note] /usr/sbin/mysqld (mysqld 5.7.11-0ubuntu6) starting as process 15128 ...
2017-04-21T13:54:55.459347Z 0 [Note] InnoDB: PUNCH HOLE support available
2017-04-21T13:54:55.459640Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-04-21T13:54:55.459733Z 0 [Note] InnoDB: Uses event mutexes
2017-04-21T13:54:55.459808Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2017-04-21T13:54:55.459882Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.8
2017-04-21T13:54:55.459956Z 0 [Note] InnoDB: Using Linux native AIO
2017-04-21T13:54:55.460825Z 0 [Note] InnoDB: Number of pools: 1
2017-04-21T13:54:55.461660Z 0 [Note] InnoDB: Not using CPU crc32 instructions
2017-04-21T13:54:55.490649Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2017-04-21T13:54:55.529734Z 0 [Note] InnoDB: Completed initialization of buffer pool
2017-04-21T13:54:55.539231Z 0 [Note] InnoDB: page_cleaner coordinator priority: -20
2017-04-21T13:54:55.666780Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2017-04-21T13:54:55.680542Z 0 [Note] InnoDB: Log scan progressed past the checkpoint lsn 6137197
2017-04-21T13:54:55.680857Z 0 [Note] InnoDB: Doing recovery: scanned up to log sequence number 6137206
2017-04-21T13:54:55.683052Z 0 [Note] InnoDB: Doing recovery: scanned up to log sequence number 6137206
2017-04-21T13:54:55.683159Z 0 [Note] InnoDB: Database was not shutdown normally!
2017-04-21T13:54:55.683234Z 0 [Note] InnoDB: Starting crash recovery.
2017-04-21T13:54:56.235783Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2017-04-21T13:54:56.236083Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2017-04-21T13:54:56.236380Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2017-04-21T13:54:56.774814Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2017-04-21T13:54:56.779067Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2017-04-21T13:54:56.779339Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2017-04-21T13:54:56.782870Z 0 [Note] InnoDB: Waiting for purge to start
2017-04-21T13:54:56.833676Z 0 [Note] InnoDB: Waiting for purge to start
2017-04-21T13:54:56.884534Z 0 [Note] InnoDB: 5.7.11 started; log sequence number 6137206
2017-04-21T13:54:56.905205Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2017-04-21T13:54:56.910750Z 0 [Note] Plugin 'FEDERATED' is disabled.
2017-04-21T13:54:56.923048Z 0 [Note] InnoDB: Buffer pool(s) load completed at 170421 16:54:56
2017-04-21T13:54:57.020024Z 0 [Warning] Failed to set up SSL because of the following SSL library error: SSL context is not usable without certificate and private key
2017-04-21T13:54:57.020302Z 0 [Note] Server hostname (bind-address): '127.0.0.1'; port: 3306
2017-04-21T13:54:57.025616Z 0 [Note] - '127.0.0.1' resolves to '127.0.0.1';
2017-04-21T13:54:57.025814Z 0 [Note] Server socket created on IP: '127.0.0.1'.
2017-04-21T13:54:57.182104Z 0 [Note] Event Scheduler: Loaded 0 events
2017-04-21T13:54:57.183364Z 0 [Note] /usr/sbin/mysqld: ready for connections.
Version: '5.7.11-0ubuntu6' socket: '/var/run/mysqld/mysqld.sock' port: 3306 (Ubuntu)
Я конечно не спец в логах, но насколько я понял, там все норм.