K
K
kslv12020-05-10 21:12:29
PHP
kslv1, 2020-05-10 21:12:29

How to display not the id of the element, but the word that is attached to it?

Good day!
More recently, I began to study working with the database and decided to immediately apply knowledge in practice during the course of training. I linked 2 tables but can't figure out how to interpret the id into a word that refers to it. I'll attach a photo and code below.

Base:
imgur base

Code:
<?php $country_name = get_country_by($seria["countries_id"]); ?> (on the page)

(in a separate file where the connection to the database is registered)
function get_country_by($id) {
global $db;
$countryN= $db->prepare('SELECT country_name FROM country WHERE id = :id');
$countryN->execute([':id' => $countries_id]);
foreach ($countryN as $country_name) {
return $country_name;
}
}

The result is the number 1, but not the name of the country.

Do not throw sticks, if nonsense is written above, it is better to throw a link where you can read about it. Thank you!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
alexalexes, 2020-05-10
@kslv1

After this line: ... you need to apply one of the methods:
$countryN->execute([':id' => $countries_id]);

$rows = $countryN->fetchAll();
var_dump($rows);

or
$row = $countryN->fetch();
var_dump($row);

Read here and here .
In short, work with the database goes through the following stages:
1) Connecting to the database (host, login password, etc.)
1.1) Handling connection errors
2) Passing encoding parameters, date/time formats, locales, etc.
3) Preparing a query ( prepare function)
3.1) Handling syntax errors in the request text.
4) Preparation of input and output query parameters ( bind function)
4.1) Handling parameter errors (the result of returning the value of the bind function).
5) Execution ( execute function).
5.1) Handling execution errors (usually, look at the return status of the execute function's value).
6) Fetching the result (fetching, we use fetch functions).
*) https://www.php.net/manual/ru/pdo.errorinfo.php getting an error status at any stage.

N
nozzy, 2020-05-10
@nozzy

foreach ($countryN as $country) {
   echo $country['country_name'];
}

A
Alex_2, 2020-05-11
@Alex_2

The query must be in both tables and contain a linking condition. Then from its results you can get your country name and not id.
Select from tab1, tab2 where tab1.id=tab2.fieldname like that, I didn't delve into the essence of your tables.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question