Hello I receive the following error:
Notice: Undefined index: $db_field.
It's because I have not declared the parameter: $db_field
- when this function is called:
if (checkInField($webmailUserName,$db_connection,$db_con_table,"userName") == false)
The fourth bit is a clear string, PHP is not like Java where your declare the variables int, long, string, etc. So I used echo $db_field
and sure enough the echo onscreen shows 'userName' so I think its recognised as a string?
I have tried echo $row[$db_field];
(does not work)
I have tried echo $row['db_field'];
(indicating a string using '
does not work / if I understand right)
I have tried echo $row['userName'];
(this string works)
I can however check with isset()
which I do not understand how to do. Other posts with my error description do not seem to match what I'm trying to achieve.
Please can someone explain to me why echo $row[]
does not recognise '$db_field'
as a string and what is needed to fix it. Hopefully this will help other beginners too.
I'm using PHP5.3 and cannot check any server ini's as I'm using a domain and webserver company for my script. (Another Undefined Index (this one's defined though))
function checkInField($value,$db_connection,$db_con_table, $db_field)
// Checks a value is not within a database field
{
$query = "SELECT $db_field FROM $db_con_table WHERE $db_field='$value'";
$result = $db_connection->query($query) or die($mysqli->error());
// GOING THROUGH THE DATA
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
echo $row['$db_field'];
}
}
else
{
echo 'NO RESULTS';
}
The warning (aka Notice) about Undefined index: $db_field
should indicate that you're trying to perform an array-index (like Map.get()
in Java) with the string $db_field
. (When you typed in '$db_field'
, you expected it to evaluate to be userName
, but it isn't.)
This is because in PHP, single-quoted strings are different than double-quoted strings. (PHP Docs)
So, instead of this:
echo $row['$db_field']; // indexing with the literal string $db_field
... use:
echo $row[$db_field]; // if $db_field is numeric, acts like List.get(int); if $db_field is a string, acts like Map.get(Object)
or
echo $row["$db_field"]; // indexing with the string-representation of the variable named $db_field
About forward-declaring variables: One of your method parameters is named $db_field
, so it's perfectly safe to refer to the variable of that name inside your method (but not outside it). I think you assumed the Undefined...
had to do with the variable itself, but that is not the case.