I get the following PHP error: undefined variable record
.
Please advise what I am doing wrong as I am new to PHP. This is part of my code and below where I'm getting the error.
if(isset($_GET['id'])){
$record = mysql_fetch_assoc(mysql_query("SELECT * from accounts WHERE id = '$_GET[id]'"));
foreach($record as $key=>$val) $record[$key] = stripslashes($val);
}
<tr>
<td width="28%"><div align="right">Name</div></td>
<td width="72%"><input type="text" name="name" value="<?php echo $record['name'] ?>"/></td>
</tr>
In your table you call <?php echo $record['name'] ?>
, but $record
is only set inside your if-statement. Meaning, if your if-statement is not true, it will be skipped and $record will never be set.
A simple fix would be to add an else clause to catch situations where no id was set.
if(isset($_GET['id'])){
$record = mysql_fetch_assoc(mysql_query("SELECT * from accounts WHERE id = '$_GET[id]'"));
foreach($record as $key=>$val) $record[$key] = stripslashes($val);
} else {
// No id set, set an empty record
$record = array('name' => null);
}
You are just accessing without the get variable id. Because of that, the variable $record is never initializated and the error prompts to your output.
You can fix it initializating it before the if statement or echo its values only if is set or not empty:
if(isset($_GET['id'])){
$record = mysql_fetch_assoc(mysql_query("SELECT * from accounts WHERE id = '$_GET[id]'"));
foreach($record as $key=>$val) $record[$key] = stripslashes($val);
}
<tr>
<td width="28%"><div align="right">Name</div></td>
<td width="72%"><input type="text" name="name" value="<?php echo (!empty($record['name']))?$record['name']:""; ?>"/></td>
</tr>