Undefined variable error in array (PHP)

Perantine

New Member
I have a collection of check boxes all with the name c[] but different values. From php8 the code below works but gives me an 'Undefined variable $sql_c’ warning (perhaps this error was just suppressed in earlier versions?). I was given the code years back and have now updated it with numerous 'if isset()' functions, but if I do that to the $sql_c function, I get no results. Any help would be appreciated.

if (isset($_POST['submit']) && isset($_POST['c'])) {

$sql="stuno,fname,lname";

if(isset($_POST['c']) && $_POST['c']=="") {$c = array(); }

foreach ($_POST['c'] as $cID) {

$sql_c .= ",".$cID; // "Undefined variable $sql_c" warning

if (isset($numCat)) {$numCat = $numCat + 1;}

}

$sql = $sql . $sql_c;

$sql="SELECT"." ".$sql." "."FROM records ORDER BY fname";

$result=@mysqli_query($dbcnx, $sql);
 

Cromewell

Administrator
Staff member
You are trying to concatenate into an uninitialized variable. Before your loop, add $sql_c = ""; to create the variable. The line erroring could be rewritten as $sql_c = $sql_c . "," . $cID; and since $sql_c has no existing value php does not know what to do.

In earlier versions, you may have gotten an implicit create with an empty value. You may even be getting one now, you just also get a warning saying it was undefined the first time though the loop.
 
Top