用全局变量查询PHP中的MySQL数据库

时间:2013-01-20 15:15:33

标签: php mysql select global-variables

我无法在php / mysql Select查询中获取全局变量。

这是我目前的代码,它不会从我的数据库中返回任何值。

<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>

如果我将选择查询的结尾更改为:

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>

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

任何人都可以帮助我。

1 个答案:

答案 0 :(得分:0)

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

<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>