1

My db table looks like that

enter image description here

I'm trying to get page title and content from this function

function page($current, $lang){
    global $db;
    $txt='txt_'.$lang;
    $title='title_'.$lang;
    $data=$db->query("SELECT '$txt', '$title' FROM pages WHERE `id`='$current'");
    $data=$data->fetch_array(MYSQLI_BOTH);
    return $data;
}

Then at the beginning of the index page getting array values

$data=page($id, $lang);

And using like this example

<title><?=$data[1]?></title>

But getting every time the same result title_en (en is my language variable.). What's wrong with my code?

1 Answer 1

6

Don't single quote your fields. MySQL interprets this as a string.

$data=$db->query("SELECT $txt, $title FROM pages WHERE `id` = $current");

Alternatively you can use backticks in MySQL. But note that $current still shouldn't have them assuming it's an integer field.

$data=$db->query("SELECT `$txt`, `$title` FROM pages WHERE `id` = $current");
Sign up to request clarification or add additional context in comments.

4 Comments

To clarify, when you single quote your fields, you are essentially asking the database for constant strings. It's like saying "give me a copy of the string $title for every row in the database"
@Robert Martin, nice additional clarification, I have added it to my answer.
$data=$db->query("SELECT n.name, p.$txt, p.$title FROM pages AS p, nav AS n WHERE id=$current"); WHAT'S WRONG IN THIS CODE?
One thing at a time friend. You should post another question if you are progressing further down the rabbit hole (as it seems from your new query).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.