Drupal 7 php запросы

Php drupal 7 db query code example

you mention you’ve put your «php» folder in ‘/sites/all’, so surely the path from your AJAX call needs to be the same: Solution 2: These days «there is a module for it» (to query external databases in formats such as Oracle, MS SQL, Postgress, SQLite, or just any PDO compliant format). Solution 1: As @SpaceBeers mentions this is really not a good way to do this kind of thing in Drupal (Google «bootstrapping Drupal» or «access custom database in Drupal» for some ideas).

Query a database with drupal 7

As @SpaceBeers mentions this is really not a good way to do this kind of thing in Drupal (Google «bootstrapping Drupal» or «access custom database in Drupal» for some ideas).

The reason your code probably isn’t working, though, is because you’re calling your AJAX in using the following code:

ajaxRequest.open(“GET”, “/php/check.php” + queryString, true); 

The problem is in the path. you mention you’ve put your «php» folder in ‘/sites/all’, so surely the path from your AJAX call needs to be the same:

ajaxRequest.open("GET", "/sites/all/php/check.php" + queryString, true); 

These days «there is a module for it» (to query external databases in formats such as Oracle, MS SQL, Postgress, SQLite, or just any PDO compliant format). It’s the Forena module (disclosure: I’m a co-maintainer of it).

Читайте также:  Icon in header html

Head over to its demo site to see it as work, and refer to its community docu for way more details. Here is a quote from its docu:

. built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

“drupal 7 db_query example” Code Answer, follow. grepper; search snippets; faq; usage docs ; install grepper; log in; signup

How to execute query in Drupal 7 block

Documentation and examples for writing db queries in Drupal are here: Database abstraction layer.

That said, it is not recommended to use the PHP filter and enter PHP in a block. It’s less secure, trickier to maintain (no version control!) and more difficult to debug if something breaks.

Drupal 8 db query Code Example, Follow. GREPPER; SEARCH SNIPPETS; FAQ; USAGE DOCS ; INSTALL GREPPER; Log In; All Languages >> PHP >> drupal 8 db query >> PHP >> drupal 8 db query

How to insert the values into database in drupal 7?

Drupal 7 uses a new database API, which includes the function db_insert() that is strongly recommended to be used in place of db_query(«INSERT»)

In your case, your code would become

function reg_fields_form_submit($form,&$form_state)< $name = trim($form_state['values']['name']); $phone = trim($form_state['values']['phone']); $email = trim($form_state['values']['email']); $result = db_insert('registration') ->fields(array( name => $name, phone => $phone, email => $email, )) ->execute(); if ($result)

Looks like drupal 7 uses ? for unnamed placeholder. So use ? instead of %s or use named placeholder.db_query

Using db_insert for insert operation is recommended.

Php — How to create a query in Drupal 8, I am used to using db_select in drupal 7 but now it’s deprecated in drupal 8. So, If I need to create a query to list all users from users_field_data table, What should I do? Do I still use db_select or db_query even though they are deprecated functions? Or create a new controller to extend from «Select class» …

Check if the entry in DB exists

You need to query the table to see if the data exists before writing to it, if a row exists matching the criteria then do nothing. For example;

function blablabla_cron() < // Begin building the query. $query = db_select('watchdog', 'th') ->extend('PagerDefault') ->orderBy('wid') ->fields('th', array('wid', 'timestamp', 'variables')) ->limit(2000); // Fetch the result set. $result = $query -> execute(); // Loop through each item and add to $row. foreach ($result as $row) < // Query Blablabla table for row matching timestamp and variables $r = db_select('blablabla', 'b') ->fields('b') ->condition('timestamp', $row->timestamp, '=') ->condition('variables', $row->variables, '=') ->execute(); // If row doesn't exist then create it (I assume blablabla_table creates?) if($r->rowCount() == 0) < blablabla_table($row); >> > 

Pretty difficult to give an example given that you’re missing the blablabla_table() function in your question, I assume it writes to the blablabla_table. In the future ask questions without placeholder names.

Laravel 8 query on blade Code Example, “laravel 8 query on blade” Code Answer. laravel query when . php by Jaskaran on Sep 14 2020 Comment

Источник

Drupal_http_request для POST, GET, PUT и других запросов в Drupal 7

Очень часто при написании сообственных модулей нам нужно отправлять http запросы на другие сервера для получения нужных данных. Примеров может быть масса от перевода текста и до расчета стоимости каких либо услуг. В drupal для этих целей служит функция drupal_http_request:

 drupal_http_request($url, array $options = array()); 
 $url:строка содержащая полный URI. array $options: массив, который может содержать заголовки, метод, данные, максимальное количество перенаправлений, таймаут. 

Возвращаемое значение
объект, который содержит тело запроса, код ответа, протокол, статук, код редиректа, ссылку редиректа, сообщения об ошибках, заголовки и конечно же ответ. Более подробно можно ознакомится на по этой ссылке

Ну что давайте теперь попробуем все на практике. Для этого я выбрал сервес перевода от Яндекса. Вот тут API Яндекса по переводу. Начнем с GET запроса. Работать я буду с JSON-интерфейсом. Согласно API Яндекса наша строка должна выглядеть следующим образом:

http://translate.yandex.net/api/v1/tr.json/translate?lang=en-ru&text=To+be,+or+not+to+be%3F&text=That+is+the+question

тут мы передаем направление перевода и строки для перевода. Самый простой метод отправить такой запрос приведен ниже:

 //создаем строку с запросом $url = 'http://translate.yandex.net/api/v1/tr.json/translate?lang=en-ru&text=To+be,+or+not+to+be%3F&text=That+is+the+question'; //отправляем запрос $result = drupal_http_request($url); //получаем ответ в виде объекта $translate = json_decode($result->data); 

здесь я опустил некоторые проверки, например код ответа и существавоние $result->data, т. к. в рамках данной статьи мы разбираем сами запросы)) итак ответ будет предоставлен в следующем виде:

 stdClass Object ( [code] => 200 [lang] => en-ru [text] => Array ( [0] => Быть или не быть? [1] => Вот в чем вопрос ) ) 

Сейчас проделаем тоже самое только POST запросом, вот код, в нем я для наглядности взял заголовок и содержимое материала:

 //загружаем объект материала $new_node = node_load(12); //создаем массив с данными, указываем направление перевода, текст перевода, заменяем пробелы на "+" и формат текста html $data = 'lang=ru-en'; $data .= '&text='.str_replace(' ', '+', $new_node->title); $data .= '&text='.str_replace(' ', '+', $new_node->body['und'][0]['value']); $data .= '&format=html'; //массив опций для запроса, указываем метод, данные, таймаут и заголовок $options = array( 'method' => 'POST', 'data' => $data, 'timeout' => 15, 'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'), ); //ну а здесь отправляем запрос и декодируем его в объект $result = drupal_http_request('http://translate.yandex.net/api/v1/tr.json/translate', $options); $translate = json_decode($result->data); 

Ну вот я и расказал вам основы работы с http запросами в Drupal, если есть какие-нибудь вопросы, пишите в комментариях.

Источник

Drupal 7 – Database Query Examples

How to do Database Queries with db_query and db_select.

– Create an article node/add/article
– Create a template for it (node–[nid].tpl.php)

Now we can test queries easily inside this template:

– Create dummy content with Devel (Generate users/generate content).

To fetch all node titles you would normally do this kind of sql statement

$sql = ‘SELECT n.title FROM node n’;

$result = db_query(‘SELECT n.title FROM n’);

foreach($result as $item) print $item->title;
>
So pretty much the same expect curly brackets are used around the table table > .
These add table prefix to your tables so that you can share your database across multiple sites.

You can limit results like this in sql :

$sql = ‘SELECT n.title FROM node n LIMIT 0,20’;
In Drupal you would do this:

$result = db_query_range(‘SELECT n.title FROM n’,0,20);

In Drupal LIMIT is abstracted in db_query_range() because of syntax differences between different databases (like in MSSQL you have to write TOP(2) to get top two rows but in MySQL you would use LIMIT 2)

In sql you use variables like this:

$sql = ‘SELECT n.title, n.uid FROM node n WHERE n.uid = $uid LIMIT 0,20’;
In Drupal you use placeholders like this:

$result = db_query_range(‘SELECT n.title, n.uid FROM n WHERE n.uid = :uid’,0,20,
array(‘:uid’ => $uid));
Placeholders are used to add a security layer that inserts variables in a secure manner so you don’t have to escape or quote them before they are added into the query.

I used foreach to iterate through the result set.

You could also get an array with this:

$result = db_query_range(‘SELECT n.title, n.uid FROM n WHERE n.uid = :uid’,0,20,
array(‘:uid’ => $uid))->fetchAll();

You can iterate through that exactly the same way:

foreach($result as $item) print $item->title;
>
If you need just one item, you can use fetchField();

$result = db_query_range(‘SELECT n.title, n.uid FROM n WHERE n.uid = :uid’,0,20,
array(‘:uid’ => $uid))->fetchField();
print $result;
3. db_select

You can also use more flexible but slower db_select() to fetch items.

Here is how to do same thing with db_select:

$result = db_select(‘node’,’n’)
->fields(‘n’,array(‘title’))
->execute();

Here you don’t use brackets around the table. it’s handled for you.

$result = db_select(‘node’,’n’)
->fields(‘n’,array(‘title’))
->range(0,20)
->execute();
Variables

$result = db_select(‘node’,’n’)
->fields(‘n’,array(‘title’,’uid’))
->range(0,20)
->condition(‘n.uid’,$uid,’=’)
->execute();

Источник

Оцените статью