-2

I have an array like this

$EN=array(
    "text1"=>"translation1",
    "text2"=>"translation2",
    "text3"=>"translation3",
    "text4"=>"translation4",
);

and this is my query

$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN';";

$test= $conn->query($result);

The langVar column will retrieve text variables and the translation column is for translation words.

$EN=array(
  foreach ($test AS $row){
    $row['langVar']=>$row['$translation']
    }
 );

but it was a syntax error

Please, how can I do this the right way ?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • you cant start an foreach loop within an array. Just define the array in common, then loop through it outside the array and push it into the array. I will refrain myself from mentioning you are wide open to SQL injections .... oh wait, i just did :P – Dorvalla Aug 19 '22 at 21:59
  • Are you asking how to fetch all records into an associative array order by one of the result's columns? – Dharman Aug 19 '22 at 22:12
  • Tons of topics about it. https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – Dorvalla Aug 19 '22 at 22:12
  • It is a very bad idea to use `die(mysqli_error($$conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Aug 19 '22 at 22:12
  • @Dharman I removed `die(mysqli_error($$conn));` according to your Advice , Thank you – Dilara Adams Aug 19 '22 at 23:26

2 Answers2

0

You can't put a loop inside an array literal.

Add to the array inside the loop, not the other way around:

$EN = [];
foreach ($test as $row) {
    $EN[$row['langVar']] = $row['translation'];
}

DEMO

Barmar
  • 741,623
  • 53
  • 500
  • 612
-1

You don't need a loop. If you only want to fetch all rows into a multidimensional array indexed by one of its columns, you cause use fetch_all() and array_column().

$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN'";
$EN = array_column($conn->query($result)->fetch_all(), 0, 1);
Dharman
  • 30,962
  • 25
  • 85
  • 135