Variable not found error
Hey, can anyone notice any errors in this code:
<?php
include("config.php");
if(isSet($_POST['lastmsg']))
{
$lastmsg = $_POST['lastmsg'];
$lastmsg 开发者_运维百科= mysql_real_escape_string($lastmsg);
$result = mysql_query("SELECT *
FROM updates
WHERE update_time < '$lastmsg'
ORDER BY msg_id DESC
LIMIT 9");
while($row=mysql_fetch_array($result))
{
$msg_id = $row['update_time'];
$message = $row['item_content'];
?>
<li>
<?php echo $message; ?>
</li>
<?php
}
?>
//More Button here $msg_id values is a last message id value.
<div id="more<?php echo $msg_id; ?>" class="morebox">
<a href="#" id="<?php echo $msg_id; ?>" class="more">more</a>
</div>
<?php
}
?>
I'm getting this error:
Notice: Undefined variable: msg_id in C:\wamp\www\stream_scripts\draft2\ajax_more.php on line 20 Call Stack #TimeMemoryFunctionLocation 10.0012373824{main}( )..\ajax_more.php:0 " class="morebox"> ( ! ) Notice: Undefined variable: msg_id in C:\wamp\www\stream_scripts\draft2\ajax_more.php on line 21 Call Stack #TimeMemoryFunctionLocation 10.0012373824{main}( )..\ajax_more.php:0 " class="more">more
Anyone can see anything wrong please comment. Thanks! :)
The issue here is if this while loop doesn't run, $msg_id
will never get set. To remedy this, set $msg_id
to a default value outside of the loop (i.e. "") or check it's existance when you want to access it
An example might be
$msg_id = "";
while(/* conditions */){
//body
}
or
while(){
$msg_id = "something";
}
if(isset($msg_id)){
// access it
}
You assume that $result always return something as $msg_id is being defined inside the while loop. You can check if msg_id has been set by inserting a condition before you try to grab your variable's value such as:
<?
if (isset($msg_id)) {
//More Button here $msg_id values is a last message id value.?>
<div id="more<?php echo $msg_id; ?>" class="morebox">
<a href="#" id="<?php echo $msg_id; ?>" class="more">more</a>
}
Also, the following lines don't look right:
</li>
<?php
}
?>
* Missing <? here *
//More Button here $msg_id values is a last message id value.
$msg_id is scoped in the while loop. You have to declare it outside the scope.
Demonstration of the problem here.
Solution:
Add this before the while loop:
$msg_id = '';
$message = '';
I hope it helps.
On the second occurence of $msg_id
, you're assuming it has already been defined, but if the while loop doesn't loop at all, it won't.
Yep. If while cycle doesn't role $msg_id wouldn't be defined. It's not an error, it's just a notice. Use error_reporting function if you don't need this message
error_reporting( E_ALL ^ E_NOTICE ) ;
Just place it in the beginning of the script
精彩评论