php pdo install ubuntu
How to install PHP5 PDO_OCI & OCI8 (and other) extensions for Ubuntu
Jul 14, 2018 · 4 min read
Updated 2015–11–10: this guide was tested to work well on Debian 7.6
I’m currently working on a PHP project that requires connection to an existing Oracle DB. We use Yii 2.0 as our PHP framework, and Ubuntu 14.10 as the development environment.
After some searching, I figured out that Yii 2.0 supports Oracle DB through PDO only (via PDO_OCI extension) that is quite old and requires some tricks to install. Official support for Oracle OCI8 is currently not yet available in Yii core, so we stuck with using PDO_OCI which is still EXPERIMENTAL.
Install Oracle Instant Client
Download Oracle Instant Client packages
First, select right client for your OS here, Instant Client for Linux x86–64 in my case for my 64-bit Ubuntu 14.10.
Then Accept License Agreement and download basic & devel rpm packages for your Oracle version. Our Oracle DB version is 11g r2, so I need to download:
Install the instant client
This will output oracle-instantclient11.2-basic-11.2.0.1.0-1.x86_64.deb & oracle-instantclient11.2-devel-11.2.0.1.0-1.x86_64.deb which can be installed via Ubuntu’s dpkg command:
Export ORACLE_HOME environment variable
We need these environment variable to compile PDO_OCI & OCI8 extensions:
Download, compile and install PHP PDO_OCI and OCI8 extensions
Download PHP source
Assuming that you already have PHP installed on your system, you just need to compile and install the extensions separately.
Then prepare pdo_oci extension for compiling using:
This will prepare configure script for you.
Note: You need php5-dev package to use phpize command. If you don’t have it on your system, just install by sudo apt-get install php5-dev
Next, proceed with configure to create Makefile :
Then run make again, the compilation should be complete now.
Finally, install the compiled extension to the system:
This will copy pdo_oci.so file to /usr/lib/php5/yyyyMMdd/pdo_oci.so
Install OCI8 and other extensions can be done easily following the same steps, with the tricks mentioned above.
Enable new extensions
The final step is to enable required extensions and restart web server (suppose you are using Apache 2 here)
Installing PDO driver on MySQL Linux server
I was suggested, not long ago, to change my code to use PDO in order to parameterize my queries and safely save HTML in the database.
Well, here are the main problems:
The site I’m building actually only requires PDO for one page. While I may consider re-writing it, it would take a while and I need the pages to be running soon, so I can’t turn off MySQL completely. If I do install PDO, will I still be able to use mysql_* handlers?
The server in question is running PHP Version 5.4.6-1ubuntu1 and Apache/2.2.22 (Ubuntu). I’m also running a phpMyAdmin database, if it matters.
6 Answers 6
On Ubuntu you should be able to install the necessary PDO parts from apt using sudo apt-get install php5-mysql
There is no limitation between using PDO and mysql_ simultaneously. You will however need to create two connections to your DB, one with mysql_ and one using PDO.
That’s a good question, but I think you just misunderstand what you read.
Install PDO
Compatibility with mysql_
Apart from the fact mysql_ is really discouraged, they are both independent. If you use PDO mysql_ is not implicated, and if you use mysql_ PDO is not required.
If you turn off PDO without changing any line in your code, you won’t have a problem. But since you started to connect and write queries with PDO, you have to keep it and give up mysql_.
Several years ago the MySQL team published a script to migrate to MySQLi. I don’t know if it can be customised, but it’s official.
Basically the answer from Jani Hartikainen is right! I upvoted his answer. What was missing on my system (based on Ubuntu 15.04) was to enable PDO Extension in my php.ini
To find where your current active php.ini file is located you can use phpinfo() or some other hints from here: https://www.ostraining.com/blog/coding/phpini-file/
At first install necessary PDO parts by running the command
where * is a version name of php like 5.6, 7.0, 7.1, 7.2
After installation you need to mention these two statements
The purpose of using this is to implement an additional layer of security between the user interface and the database. By using this layer, data can be normalized before being inserted into your data structure. (Capitals are Capitals, no leading or trailing spaces, all dates at properly formed.)
But there are a few nuances to this which you might not be aware of.
First of all, up until now, you’ve probably written all your queries in something similar to the URL, and you pass the parameters using the URL itself. Using the PDO, all of this is done under the user interface level. User interface hands off the ball to the PDO which carries it down field and plants it into the database for a 7-point TOUCHDOWN.. he gets seven points, because he got it there and did so much more securely than passing information through the URL.
You can also harden your site to SQL injection by using a data-layer. By using this intermediary layer that is the ONLY ‘player’ who talks to the database itself, I’m sure you can see how this could be much more secure. Interface to datalayer to database, datalayer to database to datalayer to interface.
By implementing best practices while writing your code you will be much happier with the outcome.
Re: MySQL Functions in the url php dot net/manual/en/ref dot pdo-mysql dot php
Re: Object Oriented Design using UML If you really want to learn more about this, this is the best book on the market, Grady Booch was the father of UML http://dl.acm.org/citation.cfm?id=291167&CFID=241218549&CFTOKEN=82813028
Or check with bitmonkey. There’s a group there I’m sure you could learn a lot with.
PHP 7 RC3: How to install missing MySQL PDO
I am trying to setup webserver with PHP 7 RC3 + Nginx on Ubuntu 14.04 (for test purposes).
I installed Ubuntu in Vagrant using ubuntu/trusty64 and PHP 7 RC 3 from Ondřej Surý (https://launchpad.net/
I can not find the way to install MySQL PDO (PHP sees PDO class but not anything related to MySQL, like PDO::MYSQL_ATTR_DIRECT_QUERY etc.)
Looks like there is no lib php7.0-mysql (by analogy with standard php5-mysqlnd and php7.0-fpm etc. from Ondřej)
Section PDO in phpinfo() :
12 Answers 12
For thoses running Linux with apache2 you need to install php-mysql
or if you are running ubuntu 16.04 or higher just running the following command will be enought, no need to edit your php.ini file
If you are running ubuntu 15.10 or below:
Edit your php.ini file, it’s located at /etc/php/[version]/apache2/php.ini and search for pdo_mysql you might found something like this
Save the file and restart apache
Check that it’s available in your phpinfo()
First install php-mysql
then enable the module
and restart apache
First, check if your php.ini has the extension enabled «php_pdo_mysql» and «php_mysqli» and the path of «extension_dir» is correct. If you need one of above configuration, then, you must restart the php-fpm to apply the changes.
In my case (where i am using the Windows OS in the company, i really prefer OSX or Linux), i solved the problem putting this values in the php.ini:
If you are on windows, and your php folder is not in your PATH, you have set the absolute directory in your php.ini
Restart apache2.4 and it should work.
make install (as root)
This worked for me
On ubuntu 18.04 following works for me
type this in your terminal
I had, pretty much, the same problem. I was able to see that PDO was enabled but I had no available drivers (using PHP 7-RC4). I managed to resolve the issue by adding the php_pdo_mysql extension to those which were enabled.
I resolved my problem on ubunto 20.4 by reinstalling php-mysql.
Then install php-mysql:
It will add new configurations in php.ini
Had the same issue, resolved by actually enabling the extension in the php.ini with the right file name. It was listed as php_pdo_mysql.so but the module name in /lib/php/modules was called just pdo_mysql.so
So just remove the «php_» prefix from the php.ini file and then restart the httpd service and it worked like a charm.
Please note that I’m using Arch and thus path names and services may be different depending on your distrubution.
I’ll start with the answer then context NOTE this fix was logged above, I’m just re-stating it for anyone googling.
make install (as root)
enable extension=mysqli.so in your php.ini file
This is logged as an answer from here (please upvote it if it helped you too): https://stackoverflow.com/a/39277373/3912517
Context: I’m trying to add LimeSurvey to the standard WordPress Docker. The single point holding me back is «PHP PDO driver library» which is «None found»
Ubuntu 16 (Ubuntu 7.3.0)
Get instructions saying all I have to do is run this:
But then I get this:
By this stage, I’m still getting this on apt-get update:
I start trying to add in php libraries, got Unicode issues, tried to get around that and. you get the idea. whack-a-mole. I gave up and looked to see if I could compile it and I found the answer I started with.
You might be wondering why I wrote so much? So that anyone googling can find this solution (including me!).
PHP: PDO быстрый старт, работа с MySQL
Содержание:
PDO (PHP Data Objects) — расширение PHP, которое реализует взаимодействие с базами данных при помощи объектов. Профит в том, что отсутствует привязка к конкретной системе управления базами данных. PDO поддерживает СУБД: MySQL, PostgreSQL, SQLite, Oracle, Microsoft SQL Server и другие.
Почему стоит использовать PDO
Тестовая база данных с таблицей
Установка PDO
Проверить доступные драйвера
Соединение с базой данных
Соединения устанавливаются автоматически при создании объекта PDO от его базового класса.
При ошибке подключения PHP выдаст ошибку:
Подготовленные и прямые запросы
В PDO два способа выполнения запросов:
Прямые запросы
Прямые запросы используются только в том случае, если в запросе отсутствуют переменные и есть уверенность, что запрос безопасен и правильно экранирован.
Подготовленные запросы
Как видно, в случае именованных плейсхолдеров в execute() должен передаваться массив, в котором ключи должны совпадать с именами плейсхолдеров. После этого можно извлечь результаты запроса:
Получение данных. Метод fetch()
Получение данных. Метод fetchColumn()
Получение данных. Метод fetchAll()
PDO и оператор LIKE
Работая с подготовленными запросами, следует понимать, что плейсхолдер может заменять только строку или число. Ни ключевое слово, ни идентификатор, ни часть строки или набор строк через плейсхолдер подставить нельзя. Поэтому для LIKE необходимо сначала подготовить строку поиска целиком, а потом ее подставлять в запрос:
Здесь может вознинуть проблема! Поиск может не работать, потому как из базы у вас приходят данные в неправильной кодировке. Необходимо добавить кодировку в подключение, если она там не указана!
PDO и оператор LIMIT
Решение #1 : Отключить режим эмуляции:
PDO и оператор IN
При выборке из таблицы необходимо доставать записи, соответствующие всем значениям массива.
Добавление записей
Изменение записей
Удаление записей
Использование транзакций
Важно! Транзакции в PDO работают только с таблицами InnoDB
В данной заметке мы познакомились с основными понятиями PDO, его установкой, подключением к БД и самые простые возможности выборки, изменения и удаления данных. В следующих заметках мы рассмотрим ещё несколько тем, касающихся PDO.
How to activate PHP7.0 PDO in 16.04 LTS?
I upgraded from 14.04LTS to 16.04LTS; php5 to php7.0; MySQL to 5.7. Apache and PHP are working but when trying to access MySQL databases, I get the following:
phpinfo() shows «no value» under PDO Drivers Enabled. Tried to compare php.ini from PHP5 but couldn’t see anything obvious. Where do I go from here?
4 Answers 4
Installing php7.0-mysql should be enough:
You will then need to ensure the module is enabled:
Then restart Apache to load the new modules:
If the problem persists, do:
You need to change preg_replace to preg_replace_callback for php7.0.
For earlier versions:
Not the answer you’re looking for? Browse other questions tagged php7 or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.