Перейти к содержимому

Как подключить базу данных к сайту php

  • автор:

PHP: работа с БД MySQL

PHP: работа с БД MySQL

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

Их используют для:

  1. Регистрации и авторизации на сайте (хранят регистрационные данные).
  2. Хранения статей и комментариев к ним.
  3. Организации поиска по веб-сайту.

В этой статье мы научимся вставлять, изменять, получать и защищать данные из БД MySQL, используя PHP.

Есть несколько вариантов подключения к базе данных MySQL, но самые лучшие варианты — mysqli и PDO .

Основная разница в том, что PDO может работать с огромным количеством баз данных: MySQL, Cubrid, Oracle, SQlite и так далее. А mysqli может работать только с MySQL.

В своей статье я покажу, как работать с PDO.

Примеры показывать буду на локальном сервере ( xampp ).

Создание БД и таблиц

Создать БД можно из панели управления хостингом, если есть такая возможность, а если нет, то из phpMyAdmin. Сравнение ставим utf8_general_ci.

Заходим в БД и создадим таблицу users , которую будем использовать для примера. Она будет включать колонки: ID(int) , login(varchar) и pass(varchar) . ID будет первичным ключом, а также будет иметь галочку напротив AI(auto increment), что позволит каждой новой записи присваивать id на 1 больше, чем у прошлой записи. Кроме этого, не забываем проставить длину varchar ’ам и поставить сравнение utf8_general_ci к полям login и pass .

База данных

Теперь мы имеем готовую БД и таблицу для работы с ней.

Подключение к БД с помощью PHP

Создаём файл index.php и прописываем:

Мы создали подключение к БД. Подключение от PDO не нужно закрывать, оно само закрывается, когда скрипт завершает свою работу.

Выборка данных

Здесь я сделаю небольшое отступление. Выбирать данные можно:

  • Ассоциативным массивом

PDO::FETCH_ASSOC — возвращает массив с названиями столбцов в виде ключей.

  • Объектом

PDO::FETCH_OBJ — возвращает анонимный объект со свойствами, соответствующими именам столбцов.

Fetch() — каждый раз извлекает следующую строку.

Продолжаем скрипт:

Здесь мы обращаемся к массиву $row по индексу login.

В данном случае код выведет логин всех, кто есть в таблице.

Здесь мы обращаемся к объекту $row по login.

В данном случае код выведет также логин всех, кто есть в таблице.

Выборка данных по параметру + защита

Мы можем выбирать определённые данные из таблицы. Например, мы можем выбрать все записи, где pass = 123, и тому подобные.

Вот первый пример выборки по логину + защита:

Можно указать несколько вопросительных знаков, а в execute перечислить замены для них через запятую.

Вот второй пример выборки по логину + защита:

Можно указать несколько ключей, а в execute перечислить замены для них через запятую в формате ‘ключ’ => значение .

Второй способ использовать предпочтительнее, так как читаемость и понятность кода более понятна, чем в первом примере, но использовать можно два способа.

Вставка данных по параметру + защита

Теперь можем проверить таблицу. Видим, что всё сработало правильно.

Обновление данных по параметру + защита

Теперь можем проверить таблицу. Видим, что всё сработало правильно.

Заключение

Как видите, работать с PDO довольно легко. Теперь вы сами можете создавать веб-сайты с базами данных.

Надеюсь, что вам понравилась статья, и вы получили новые знания.

mysql_connect

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

  • mysqli_connect()
  • PDO::__construct()

Description

Opens or reuses a connection to a MySQL server.

Parameters

The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost.

If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'. In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used.

The username. Default value is defined by mysql.default_user. In SQL safe mode, this parameter is ignored and the name of the user that owns the server process is used.

The password. Default value is defined by mysql.default_password. In SQL safe mode, this parameter is ignored and empty password is used.

If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored.

The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL , MYSQL_CLIENT_COMPRESS , MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE . Read the section about MySQL client constants for further information. In SQL safe mode, this parameter is ignored.

Return Values

Returns a MySQL link identifier on success or false on failure.

Examples

Example #1 mysql_connect() example

Example #2 mysql_connect() example using hostname:port syntax

<?php
// we connect to example.com and port 3307
$link = mysql_connect ( ‘example.com:3307’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) <
die( ‘Could not connect: ‘ . mysql_error ());
>
echo ‘Connected successfully’ ;
mysql_close ( $link );

// we connect to localhost at port 3307
$link = mysql_connect ( ‘127.0.0.1:3307’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) <
die( ‘Could not connect: ‘ . mysql_error ());
>
echo ‘Connected successfully’ ;
mysql_close ( $link );
?>

Example #3 mysql_connect() example using ":/path/to/socket" syntax

<?php
// we connect to localhost and socket e.g. /tmp/mysql.sock

// variant 1: omit localhost
$link = mysql_connect ( ‘:/tmp/mysql’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) <
die( ‘Could not connect: ‘ . mysql_error ());
>
echo ‘Connected successfully’ ;
mysql_close ( $link );

// variant 2: with localhost
$link = mysql_connect ( ‘localhost:/tmp/mysql.sock’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) <
die( ‘Could not connect: ‘ . mysql_error ());
>
echo ‘Connected successfully’ ;
mysql_close ( $link );
?>

Notes

Note:

Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library will override this and try to connect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost". If the MySQL client library tries to connect to the wrong local socket, the correct path should be set as mysql.default_host in php.ini and the server field left blank.

Note:

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close() .

Note:

Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E . On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock.

See Also

  • mysql_pconnect() — Open a persistent connection to a MySQL server
  • mysql_close() — Close MySQL connection

User Contributed Notes 36 notes

Be carefull here if you use utf8.

The file db.opt of your database should contain the following lines:
default-character-set=utf8
default-collation=utf8_general_ci

It means that your database is created to use the utf8 characterset.
One way to accomplish this is:
CREATE DATABASE my_database DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

Then, after connecting to it from PHP you should use:
mysql_set_charset(«UTF8», $connection);

If you don’t do this, you will get ugly problems in case other software is reading and writing to the same database.

The too many connections issue can be due to several problems.

1. you are using pconnect. This can tie up many connections and is not really needed for MySQL as new connections are really fast.

2. Apache children are hanging around for too long — combine this with pconnect and you have recipe for disaster.

Suggestions: reduce the amount of time apache child processes stay connected to the client and how many connections before they are killed off. And don’t use pconnect.

In case anyone else is getting «Client does not support authentication protocol requested by server; consider upgrading MySQL client» error. The problem is the new password hashing method used by MySQL >= 4.1 mentioned below.

Either update your PHP to v5 where the new password hashing is supported or use old_password() in MySQL 4.1.

UPDATE mysql.user SET password=old_password(«youroldhashpassword») WHERE user =’youruserid’ and host =’yourhost’

<?php
$server = ‘y.com’ ;
$login = ‘x’ ;
$pass = ‘x’ ;
$db = ‘x’ ;

$spojeni = mysql_connect ( $server , $login , $pass ) or die ( ‘nelze se pripojit’ );
mysql_select_db ( $db , $spojeni );
mysql_query ( «Set names ‘utf8′» );
?>

Hopefully this saves someone some grief.

My dev computer is windows and runs wampserver. I have frequent problems with PHP being unable to connect to MySQL after periods of extreme DB activity.

Long story short, it was because I was not running mysql via named-pipes and Windows was running out of available ports to serve PHP. Apparently, on windows, you have 5000 ports to work with and once they are opened, they remain so for 120 seconds before being released. This causes problems with mysql/networking because a new port is requested for each connection.

You can read more about the problem at:
(Link too long and had to be broken up)
http://dev.mysql.com/doc/refman/5.0/en
/can-not-connect-to-server.html#can-not-connect-to-server-on-windows
?>

Since mysql is on localhost, I can just enable named-pipes (which is how you should have mysql setup if you don’t need networking) to get around the problem instead of the workaround listed on that page.

The use of mysql connections can become tricky with objects. I am using mysql_connect() in a database class I wrote and the class destructor calls mysql_close. Because I have several of these database objects, mysql_connect reuses existing connections. This is fine except when the script reaches the end of execution and PHP’s garabage collection calls all the objects’ __destruct() functions. mysql_close() throws a warning that the connection is invalid, in my case for one object. This is happening with objects which use an existing connection, as the connection has already been closed. I solved the problem by forcing mysql_connect() to create a new connection each time. This is not efficient but is sufficient for my purposes for now.

I wouldn’t say this is a bug per-se, but it’s something to look out for. I imagine using mysqli is the ultimate solution.

Sometimes, I want that MySQL service start automatically when my app need it. This is specially true if you work in a development PC and/or in an small intranet environment.

You can do something like this: if the mysql_connect() function returns FALSE, try to force the initialization of the MySQL service!

For example, under Windows:

$link = @ mysql_connect ( $server , $user , $pass );
if (empty( $link )) <
@ exec ( «%SystemRoot%\\system32\\net.exe start mysql» );
sleep ( 5 );
$link = @ mysql_connect ( $servidor , $usuario , $clave );
>

?>

In Linux of course you can try «/etc/init.d/mysqld start» but you will need special permissions.

if between first and second call with same arguments there was another call with another argument, initial connection link is not reused, but new connection is created instead, regardless of new_link argument.

for example, here only one single link will be opened and then reused:
<?php
$link1 = mysql_connect ( «localhost» );
$link2 = mysql_connect ( «localhost» );
?>

and here _three_ separate links will be opened:
<?php
$link1 = mysql_connect ( «localhost» );
$link3 = mysql_connect ( «127.0.0.1» );
$link2 = mysql_connect ( «localhost» );
?>

so if you wanted to switch between connections just by call to mysql_connect, and rely on its internal link caching, you can be wasting your database connections.

Whenever you open two connections to a single database,
you are likely not to get any error when selecting not existing db.

<?php
$db1 = mysql_connect ( . );
mysql_select_db ( ‘existing_db’ , $db1 );

$db2 = mysql_connect ( . );
mysql_select_db ( ‘not_existing_db’ , $db2 );

mysql_query (. , $db2 );
//will return no errors and the query wouldn’t be executed.
?>

Pay attention and you may save few hours of debugging.

to use load data local infile function from mysql (at mysql 4.0.16, php 4.3.3), set fifth parameter of mysql_connect() to CLIENT_LOCAL_FILES(128), which based on MYSQL C API ( also mysql server support load file, check by «show variables like ‘local_infile’ «)

Thank ‘phpweb at eden2 dot com’ to point this out

The addition of entries to httpd.conf to stop .inc files being served by Apache is certainly useful and to be recommended.

But it doesn’t change the fact that these files have to be readable by Apache so that the PHP processor can get at them.

As long as your don’t have multiple, possibly untrusted, users on your machine then that’s OK. But when you are running a large multi-user service with thousands of users its always possible that one of them will look at your .inc files and take a note of the passwords you have in them. They could even copy them into their own scripts and modify your databases!

Even if local users are trusted, there is always the possibility of a rogue script (PHP or some nastier language) being installed by an ignorant user. That script might then read your .inc files (whether or not they are in the web publishing tree) and expose your password.

Another solution to the security problems of putting usernames and passwords into scripts. I haven’t found this documented anywhere else so thought I’d suggest it for the online documentation. .

Don’t put passwords for mysql into scripts which may be read by any user on the machine. Instead put them into an Apache configuration file and make sure that it is not world-readable. (Apache reads its main config files as root.)

For example, add this to your httpd.conf (and chmod it to 600 or 660) then tell your apache to reload itself (apachectl graceful).

<Directory /var/www/html/mydatabase>
php_value mysql.default_user fred
php_value mysql.default_password secret
php_value mysql.default_host server.example.com
</Directory>

Then all you need in your PHP code is

$handle = mysql_connect() or die(mysql_error());

The passwords etc will only be picked up by scripts running in the named directory (or a sub-directory). The same may be done for virtualhosts etc.

If you don’t want to keep reloading your Apache server then you ay test things putting the php_value directives into a (world readable) .htaccess file. (Clearly not for production use.)

If you need to debug the values that are being supplied (or not) then use this snippet:

@syslog(LOG_DEBUG, «Using user=».ini_get(«mysql.default_user»).
» pass=».ini_get(«mysql.default_password»).
» host=».ini_get(«mysql.default_host»));

(This assumes that you are not running in ‘safe_mode’ and that you are on a unix of some sort.)

My situation: «I could connect to MySQL from the PHP via Apache and MySQL via the MySQL console, and could not connect via the PHP»

But, PHP only can connect to MySQL using mysql_connect(«localhost», «root», «password»);

«Its selinux not allowing apache to make remote connections»

Solution:
setsebool -P httpd_can_network_connect=1

Recently, I saw an obscure problem where I could connect to MySQL from the PHP via Apache and MySQL via the MySQL console, and could not connect via the PHP-CLI. This was in Windows (XP). I usually use MySQLi extension, but also tried MySQL, and both refused to work.

I restarted the service multiple times, and the PHP-CLI still would not connect.

This eventually cleared up.

I made sure to stop the service. Then, I downloaded a zipped binary-package from dev.mysql.com and started the server a few times from the commandline (mysqld/mysqld-nt, where mysqld-nt is tuned specifically for Windows) and stopped it («mysqladmin shutdown»). I was then able to successfully connect from the PHP-CLI («php -r «mysql_connect(‘localhost’, ‘root’, »); «).

Making sure it was stopped, I started the regular server from the commandline, and that was then successful. I then stopped it and started it via the Services panel, and everything still worked.

I’m assuming that when the service was restarted initially, there was a component that had died and refused to be shutdown even though the service appeared to be stopped, but shutting it down via mysqladmin killed everything entirely.

The post from ‘Graham_Rule at ed dot ac dot uk’ should include the following WARNING:

WARING: THE VALUES OF THESE DIRECTIVES WILL BE EXPOSED IF ANY OF THE CODE INCLUDES THE phpinfo() FUNCTION.

The phpinfo() function will print these values clear as day. I highly suggest against this method of storing MySQL authentication information.

I recommend creating connect and cleanup functions in a separate include file. If security is a concern, locate the include file outside of your web root folder.

<?php
$g_link = false ;

function GetMyConnection ()
<
global $g_link ;
if( $g_link )
return $g_link ;
$g_link = mysql_connect ( ‘host.name’ , ‘user’ , ‘password’ ) or die( ‘Could not connect to server.’ );
mysql_select_db ( ‘database_name’ , $g_link ) or die( ‘Could not select database.’ );
return $g_link ;
>

function CleanUpDB ()
<
global $g_link ;
if( $g_link != false )
mysql_close ( $g_link );
$g_link = false ;
>

?>

Simply include your connnection.php file in your script and anywhere you use the mysql_query() function include a call to the GetMyConnection() function.

<?php
$res = mysql_query ( «SELECT . » , GetMyConnection () );
?>

If you are trying to open multiple, separate MySQL connections with the same MySQL user, password, and hostname, you must set $new_link = TRUE to prevent mysql_connect from using an existing connection.

For example, you are opening two separate connections to two different databases (but on the same host, and with the same user and password):

$db1 = mysql_connect($dbhost, $dbuser, $dbpass);
$rv = mysql_select_db($dbname1, $db1);
$db2 = mysql_connect($dbhost, $dbuser, $dbpass);
$rv = mysql_select_db($dbname2, $db2);

At this point, both $db1 and $db2 will have selected the database named by $dbname2.

The workaround is to require that the second MySQL connection is new:

$db1 = mysql_connect($dbhost, $dbuser, $dbpass);
$rv = mysql_select_db($dbname1, $db1);
$db2 = mysql_connect($dbhost, $dbuser, $dbpass, TRUE);
$rv = mysql_select_db($dbname2, $db2);

Now, $db1 should have selected $dbname1, and $db2 should have selected $dbname2.

This has been documented on the mysql_select_db page as well.

Note: This occurs only when the server, username, and password parameters are identical for each mysql_connect statement.

Portable connections: If you migrate your source code from one to different servers and you would like to avoid re-configuration on a new serve, user the $_SERVER[‘SERVER_NAME’] flag as:

<?php
switch( $_SERVER [ ‘SERVER_NAME’ ])
<
case ‘server1.example.com’ :
mysqlconnect ( ‘host1’ , ‘user1’ , ‘password1’ );
mysql_select_db ( ‘db1’ );
break;
case ‘server2.example.com’ :
mysqlconnect ( ‘host2’ , ‘user2’ , ‘password2’ );
mysql_select_db ( ‘db2’ );
break;
>
?>

This makes a conditional connection to mysql database. It automatically chooses the correct server according to the server name from where your script runs.

Hopefully, you like this portable configuration.

If you prefer to use a hostname instead of an ip on your connection string in a script (to be able to change the ip at will), but don’t want the overhead of dns lookups, just add it to your /etc/hosts file (in windows: %WINDIR%/system32/drivers/etc/hosts).

For example, add the following to your hosts file (changing the bogus ip to your server’s real ip):

Note: On linux, make sure you have «order: hosts,bind» on your /etc/host.conf file.

On a script, make the mysql connection like so:

<?
$sid = mysql_connect («mysqlserver1», «user», «pass»);
?>

Note: this sample is in php, but it can be any other programming language (just type «ping mysqlserver1» on a prompt, on your server)

And there you have it! If your server ever gets assigned a different ip, just update the hosts file with the new one (every script will work as-is, even if under different hostnames).

A little note if your scripts sleep a lot, you want to run exactly the same SQL statement 2+ times and you have the «MySQL has gone away» error a lot.

Try setting the 4th parameter to TRUE as it seems sometimes PHP doesn’t spot that resource ID x which it used for the last identical lookup is now dud and so tries to use it, thus bypassing tests such as is_resource() and causing a failure.

This is for when mysql_ping() doesn’t work for your situation of course.

hello,every one.
do use «127.0.0.1» instead of «localhost» for php5.4-win7 if you feel the speed is slow.because win7 use ipv6 default.
«localhost» is for ipv4.

I just wanted to share a common wrapper that I use for executing one line SQL statements. Its an easy wrapper to use that takes care of the connection open/close. Optionally, the mysql_connect can be replaced with mysql_pconnect for persistent connections.

function executeQuery( $query, $db, $nocon )
<
if( $nocon != «nocon» )
if( $db != «» ) connect( $db );
else connect( «pascal_crm» );

$result= mysql_query( $query );
$err = mysql_error();
if( $err != «» ) echo «error=$err «;

if( $nocon != «nocon» )
mysql_close();
return $result;
>

PHP: как подключиться к базе данных mySQL

PHP: как подключиться к базе данных mySQL

PHP — это язык программирования на стороне сервера для обработки HTTP-запросов. К HTTP-запросам относятся:

GET — позволяет читать данные из того места, где они хранятся. Обычно это делается с помощью запроса к базе данных (MySQL).

POST — для отправки пользовательских данных, обычно, из HTML-формы. PHP позволяет получить доступ к глобальной переменной $_POST и сохранить ее значение. При этом сам PHP позволяет создавать, читать, обновлять, уничтожать БД.

Что же на самом деле происходит в процессе установки, что позволяет всем перечисленным компонентам работать вместе? Ведь если Apache и PHP, по сути, отдельные программы, то как они работают вместе над обслуживанием файла? Все просто: PHP-скрипт нужно настроить так, чтобы он подключился к базе данных SQL, прежде чем мы сможем использовать соответствующую базу данных (функция mysqli_connect).

Важно: обычно HTML-страница вызывает скрипт через пользовательскую форму ввода. И при непосредственном вводе данных как раз и происходит их добавление в базу данных. И тут должно быть соблюдено важное условие: они должны находиться на одном сервере и на одном домене. Таким образом, локальность всего программирования остается в силе.

Итак, резюмируем роли PHP и mySQL простыми словами:

PHP — как командир (программист пишет код и отдает указания языку, что и как делать).

MySQL — хранит информацию (как база данных).

Скрипт на PHP манипулирует, анализирует и создает новые данные на основе двух факторов:

a) Пользовательские данные (которые в конечном итоге и попадают в базу данных).

b) Данные, которые уже находятся в mySQL.

Как это работает

MySQL — это реляционная система управления базами данных, которая сочетает в себе стандарты SQL и функциональность РСУБД.

Вообще любой проект, независимо от его масштабов, может быть реализован с помощью MySQL. С помощью этой технологии БД можно управлять огромными объемами данных — без ущерба для их качества. Вы также можете использовать решения на базе PHP для веба — для организации доступа к огромным наборам данных из связанной или распределенной базы данных. PHP поддерживает множество баз данных, включая MySQL, MariaDB, MongoDB, Oracle и другие.

Подключение к БД с помощью PHP становится сверхважным: если скрипт не сможет подключиться к такой базе данных, запросы к ней будут неудачными.

Хорошей идеей при настройке БД является указание в начале скрипта:

названия самой базы данных.

Таким образом, если понадобится обновить БД позже, сделать это получится гораздо быстрее.

Вернёмся к тому, как именно PHP подключается к БД. Так в PHP существует три метода подключения к MySQL через бэкенд:

Рассмотрим синтаксис для всех трёх вариантов ниже.

Синтаксис MySQLi, «процедурный» способ:

Синтаксис: MySQLi, «объектно-ориентированный» способ:

Подключение к БД через функцию MySQLi

Учитывая все вышесказанное становится понятно: подключение PHP к базе данных MySQL — довольно простая задача.

Допустим, у нас есть БД со следующими данными:

Имя хоста — localhost.

Имя пользователя — root.

Чтобы установить соединение с базой данных используем функцию mysqli_connect(). Например, вот так:

Чтобы проверить, было ли соединение установлено успешно, используйте следующий код:

Как сделать выборку данных по параметру + защита

На этом этапе у вас уже должен быть файл index.php. Но, если его нет — используйте шаблон, который мы дадим ниже:

Проверяем. Готово! Всё работает корректно. Теперь нужно будет выбрать данные.

Допустим, нам нужно сделать перебор на основе ассоциативного массива. Для этого создаём соответствующий запрос (выбор из определённой группы пользователей, по логинам) и прописываем перебор в цикле while. Код может быть таким:

Не забывайте, что выборку данных можно осуществлять не только по ассоциативным массивам, но и с помощью объектов (соответственно, PDO::FETCH_OBJ).

PHP — неотъемлемая часть бэкенд-разработки в 2023 году. Успей попасть в группу сегодня и получи профессию разработчика уже завтра!

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

Как выбрать данные по параметру

При необходимости можно создать выборку только по нужным данным в таблице. Например, как в этом случае:

(обратите внимание: в execute указаны замены для нескольких ключей и указываются такие замены в формате ‘ключ’ => значение)

Существуют и другие способы выбрать данные по параметру, но вышеуказанный мы демонстрируем как самый удобный и читаемый.

Проверка соединения

Должна проводиться обязательно. Ведь множество факторов может привести к тому, что mySQL будет закрывать все попытки подключения: от некорректных параметров соединения до высоких пингов.

Чтобы проверить соединение с mySQL, используйте стандартную функцию mysqli_connect(). Вы сразу увидите удалось ли установить соединение, если же соединения не установлено — функция вернёт значение false.

Установка кодировки

Когда соединение установлено и предварительно всё функционирует корректно — сразу приступаем к установке кодировки, в противном случае можно получить кракозябры.

Чтобы установить кодировку UTF8 для MySQLi используйте стандартную конструкцию:

Заключение

В этом разделе подытожим основную информацию, которая пригодится начинающему программисту.

Что нужно знать

Чтобы успешно подключить PHP-скрипт к mySQL необходимо хотя бы базовое представление об этих технологиях (а также об MySQLi и PDO).

Что выбрать

MySQLi и PDO имеют свои преимущества. Важно помнить, что MySQLi предназначен только для баз данных MySQL. И если вы захотите использовать другую БД, придется переписать весь код. А вот PDO умеет подключаться к десятку различных баз данных, что значительно упрощает процесс перехода.

Можно использовать любой из трех перечисленных выше подходов (mySQL, mySQLi, PDO).

Связка PHP и MySQL часто используется, когда нужна высокая читабельность кода и соответствие его заданной структуре.

Изучение обеих технологий может принести пользу в долгосрочной перспективе. Ну а чтобы пользы было ещё больше — успейте записаться на курс бэкенд-разработчик от Loft.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *