0

This is my PHP PDO code:

<?php
$number = 1;
function result($conn) {
    $sql = 'SELECT name FROM customerdata';
    foreach ($conn->query($sql) as $row) {
        print " ". $number ."       ". $row['name'] . " <br> "; // this is line 6 

    }
}
result($conn);
?>

This is the error, I am getting:

Notice: Undefined variable: number in C:\xampp\htdocs\website\a.php on line 6
e4c5
  • 48,268
  • 10
  • 82
  • 117

4 Answers4

0

Pass the number variable as a parameter in the function. The number variable does not exist in that function. As said, either pass as a parameter or declare the number variable as a global variable in the function

Rotimi
  • 4,494
  • 4
  • 16
  • 27
0
$number

is a variable. You should do this

function result($conn) {
    insert line   global $number;
    $sql = 'SELECT name FROM customerdata';
    foreach ($conn->query($sql) as $row) {
        print " ". $number ."       ". $row['name'] . " <br> "; // this is line 6 

    }
}
0

You need pass the number as a arugument to the function

 function result($conn,$number) {
     $sql = 'SELECT name FROM customerdata';
        foreach ($conn->query($sql) as $row) {
            print " ". $number ."       ". $row['name'] . " <br> "; 

        }

    }
Arun Kumaresh
  • 5,734
  • 5
  • 28
  • 45
  • Worked. Your answer and Alexios answer do the same thing in all conditions? – Shilpa Choudhary Jun 03 '17 at 05:54
  • usage global in php is considered to be bad practice check it here https://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why.Instead of that pass the variable as parameter to the function – Arun Kumaresh Jun 03 '17 at 05:58
0

You can use two options here either pass $number as argument or declare it at global

Sol 1:

<?php
$number = 1;
function result($conn,$number) {
    $sql = 'SELECT name FROM customerdata';
    foreach ($conn->query($sql) as $row) {
        print " ". $number ."       ". $row['name'] . " <br> "; // this is line 6 

    }
}
result($conn,$number);
?>

Sol 2:

<?php
$number = 1;
function result($conn) {
    global $number;
    $sql = 'SELECT name FROM customerdata';
    foreach ($conn->query($sql) as $row) {
        print " ". $number ."       ". $row['name'] . " <br> "; // this is line 6 

    }
}
result($conn);
?>
B. Desai
  • 16,092
  • 5
  • 22
  • 43
  • Both do the same thing under all conditions? – Shilpa Choudhary Jun 03 '17 at 05:56
  • I recommended to use sol1 to pass variable as argument. As global declaration is not good practice. https://stackoverflow.com/questions/2216340/the-advantage-disadvantage-between-global-variables-and-function-parameters-in – B. Desai Jun 03 '17 at 06:03