-2

Why is php not able to declare a function more than one time? I am using while loop with mySQL that contains list of IDs and I am trying to parse the ID to this function. But I get Fatal error: Cannot redeclare GetValue() (previously declared.... How do I fix this?

<?php
session_start();
ob_start();


$id = "";
$db = new PDO("mysql:host=localhost; dbname="DB";charset=utf8",'uid','');

$sqlID = "SELECT ID FROM Zip";
$stmtID = $db->query($sqlID);

$pdfArray = array();

while($dataID = $stmtID->fetch(PDO::FETCH_OBJ)){

    $id = $dataID->ID;

    $sql = "SELECT * FROM Datas WHERE ID = '$id'";
    $stmt = $db->query($sql);
    GetValue($id);
}

function GetValue($x){

//
}

?>
Arthur
  • 45
  • 5
  • 1
    Try showing (or investigating) what was in `....` - it probably tells you exactly the original declaration location. https://stackoverflow.com/a/1953870/17856705 – Computable May 14 '22 at 22:29
  • @B__ but why? and how do fix it? – Arthur May 14 '22 at 22:34
  • Aside from being open to SQL injections, you can use a `join` and only execute the query once. `SELECT d.* FROM Zip as z join Datas as d on z.id = d.id` – user3783243 May 14 '22 at 22:34
  • Is `function GetValue($x){` in a loop? There's no reason to declare a function more than once, it also wouldn't make sense. How would you know that `GetValue($x)` was calling `function GetValue($x){` or `function GetValue($y){`? – user3783243 May 14 '22 at 23:20
  • I dont understand why I can't call a function multiple times? As you see that function takes in variable that gets generated from the sql table, so yes in a loop. So it is required as for my rest of the code. I cannot create 100s of same function with different names right? What is the alternative? – Arthur May 14 '22 at 23:24
  • `Cannot redeclare` means you have `function ...()` more than once. The call, `GetValue($id);` is not the issue. The question doesn't have enough details to assist, the code here wouldn't produce this error. Perhaps you are including/requiring in a loop? – user3783243 May 15 '22 at 01:21

1 Answers1

-2

instead of:

GetValue($x){

//
}

try:

function GetValue($x){

//
}
Moebius
  • 640
  • 4
  • 9
  • There is no difference with the answer. You have changed the function call to a function definition. The error is `Cannot redeclare` so instead of defining the function 2 times, which already was occurring, this answer is defining the function for a third time. – user3783243 May 15 '22 at 11:41