0

I have no clue how to do this. I've looked up examples but it is all kind of vague for me using the @variable, I have no clue on what that is and how I can look up my answer.

I've got this variable $slotname which can be weapon or amulet or anything. In my database it is weapon_name or amulet_name thats why the ._name. after the post

$slotname = $_POST['slot'].'_name';
$naam = 'Player1';
$sql = $db->prepare("SELECT @slotname FROM player WHERE naam = :naam");
$sql->execute(array(":naam" => $naam));
$fetch = $sql->fetch();

So in this case $slotname = weapon_name and I want to select the column weapon_name from the user Player1 but I have no clue how to do this. Any tips?

answer_me
  • 3
  • 6
  • $db->query("SET @slotname=$slotname"); before prepare statement – Sugumar Venkatesan May 24 '16 at 13:47
  • Because of the way parametrised/prepared queries work, you cannot bind a value to the columns select or the table it's selecting from. http://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-or-column-name-as-parameter – ʰᵈˑ May 24 '16 at 14:37

2 Answers2

1

Your database structure is essentially wrong.

There should be no such thing like slot_name field.

there should be a distinct table slots where all the slots have to be stored, and selected by values, not field names.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • And how do I do that? Every `slot` needs a name and a value. For example `weapon_slot` `3` `amulet_slot` `2` I have no clue what you mean by your answer. Could you perhaps explain? – answer_me May 24 '16 at 14:01
  • It's already clear - another table. that consists of columns `char_id`,`slot`,`item_id`. From this table you can easily select any equipment – Your Common Sense May 24 '16 at 14:09
-2
sql = $db->prepare("SELECT ".$slotname." FROM player WHERE naam = :naam");
Netham
  • 1,168
  • 6
  • 16
  • Code-only answers are discouraged. – ʰᵈˑ May 24 '16 at 14:35
  • not working @netham it just returns the same name. When $slotname = weapon_name it returns this : Array ( [weapon_name] => weapon_name [0] => weapon_name ) while it should return Array ( [weapon_name] => golden sword [0] => golden sword ) – answer_me May 24 '16 at 14:44
  • @ʰᵈˑ I know, but maybe if you see the question and the answer, putting any explanation won't help. It's that simple. If it can, and you believe in it, I welcome you to use the edit button, and edit answers, before simply downvoting because you saw a code only answer. Is it always black and white? No, i guess. – Netham May 24 '16 at 14:53
  • @answer_me Give it a try now. I made a slight change. The basic idea is to concatenate and get a string. Try to echo that string and see what query form you are getting. – Netham May 24 '16 at 14:59