使用全局变量查询MySQL数据库



我在php/mysql选择查询中获得全局变量工作。

这是我现在的代码,它没有从我的数据库返回任何值。

<HTML>
<HEAD>
<SCRIPT type="text/javascript">
window.onload = function()
{
    document.getElementById('wall').innerHTML="<?php zoomLevelOne();?>";
}
</SCRIPT>
<?php
$startBrick = rand (1, 4);
function zoomLevelOne()
{
    global $startBrick;
    $brickNo = rand (1, 4);
    $con = mysql_connect("localhost","root","password");
    if(!$con){die('Could not connect: ' . mysql_error());}
    mysql_select_db("wall", $con);
    $result = mysql_query("SELECT * FROM bricks WHERE BrickNo=$startBrick");
    $brick = mysql_fetch_array($result);
    mysql_close($con);
    echo $brick['year'];
}
?>
</HEAD>
<BODY>
<DIV id='wall'>
</DIV>
</BODY>
</HTML>

如果我将select查询的结尾改为:

WHERE BrickNo=$brickNo");

所以整个代码是这样的:

<HTML>
<HEAD>
<SCRIPT type="text/javascript">
window.onload = function()
{
    document.getElementById('wall').innerHTML="<?php zoomLevelOne();?>";
}
</SCRIPT>
<?php
$startBrick = rand (1, 4);
function zoomLevelOne()
{
    global $startBrick;
    $brickNo = rand (1, 4);
    $con = mysql_connect("localhost","root","password");
    if(!$con){die('Could not connect: ' . mysql_error());}
    mysql_select_db("wall", $con);
    $result = mysql_query("SELECT * FROM bricks WHERE BrickNo=$brickNo");
    $brick = mysql_fetch_array($result);
    mysql_close($con);
    echo $brick['year'];
}
?>
</HEAD>
<BODY>
<DIV id='wall'>
</DIV>
</BODY>
</HTML>

这对我来说似乎是正确的,因为我所做的就是将局部变量更改为全局变量,但它不起作用,所以也许我做错了什么,或者只是我的编码不好。

有谁能帮我吗

对我来说答案很简单。代码在声明变量之前调用函数。只需将脚本块移动到定义函数之后,就在标记之前。

<HTML>
<HEAD>
<?php
$startBrick = rand (1, 4);
function zoomLevelOne()
{
    global $startBrick;
    $brickNo = rand (1, 4);
    $con = mysql_connect("localhost","root","password");
    if(!$con){die('Could not connect: ' . mysql_error());}
    mysql_select_db("wall", $con);
    $result = mysql_query("SELECT * FROM bricks WHERE BrickNo=$startBrick");
    $brick = mysql_fetch_array($result);
    mysql_close($con);
    echo $brick['year'];
}
?>
<SCRIPT type="text/javascript">
window.onload = function()
{
    document.getElementById('wall').innerHTML="<?php zoomLevelOne();?>";
}
</SCRIPT>
</HEAD>
<BODY>
<DIV id='wall'>
</DIV>
</BODY>
</HTML>

相关内容

  • 没有找到相关文章

最新更新