我在stackoverflow中检查了相同类型的错误的多个线程,但我找不到我的查询的答案,所以我发布了这个问题。
我正在使用jquery Ajax将变量传递给PHP并返回结果,但我收到以下错误
注意:未定义的变量:C:\ fpl \ checkCaptain.php上的队长 22 null
以下是我正在使用的jQuery和PHP脚本。
jQuery AJAX:
$( '#outPlayer')。改变(函数(){
$阿贾克斯({
类型:“GET”,
url:“checkCaptain.php”,
数据:'q ='+ $('#OutPlayer')。val(),
成功:功能(msg){
if(msg == 1)
{$( '#测试')HTML(MSG)。 }
否则
{$( '#测试')HTML(MSG)。 }
}
PHP页面
include_once("includes/mySqlConnect.php");
$query = sprintf("SELECT MAX(gameweek) AS gameweek FROM gameweek");
$sql = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($sql))
{
$gameweek = $row['gameweek'];
}
$outPlayer = $_GET['q'];
$query1 = sprintf("SELECT captain FROM gameweek WHERE gameweek = '%s' AND player = '%s'", $gameweek, $outPlayer);
$sql1 = mysql_query($query1) or die(mysql_error());
while($row1 = mysql_fetch_array($sql1))
{
$captain = $row1['captain'];
}
echo $captain;
我真的很感激这里的快速帮助。提前致谢!!如果有愚蠢的错误,请道歉。我是Ajax和PHP的新手:)
答案 0 :(得分:2)
由于$captain
在while内定义,因此发生此错误。如果此查询产生了0行,那么您的$captain
将被定义为错误。您应该始终初始化变量。
$outPlayer = $_GET['q'];
$query1 = sprintf("SELECT captain FROM gameweek WHERE gameweek = '%s' AND player = '%s'", $gameweek, $outPlayer);
$sql1 = mysql_query($query1) or die(mysql_error());
$captain = 0; // initialize always!
if(mysql_num_rows($sql1) > 0) {
while($row1 = mysql_fetch_array($sql1)) {
$captain = $row1['captain'];
}
}
echo $captain;
exit;
强制性注释:
Please, don't use
mysql_*
functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDO或MySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial。
答案 1 :(得分:-1)
可能你必须改变
data: 'q='+$('#OutPlayer').val(),
到this
值,如
$('#outPlayer').change(function(){
var selected_val = $(this).val();
$.ajax({
type: "GET",
url: "checkCaptain.php",
data: 'q='+selected_val,
success: function(msg){
if(msg == 1)
{ $('#test').html(msg); }
else
{ $('#test').html(msg); }
});