0

我是编程新手,我的代码需要帮助。我希望我的页面提示我是否还有可用房间。我在管理页面上使用 onload 功能。

到目前为止,这是我的代码

function prompt()
{
< ?php 
include("dbconfig.php");

$sql = "SELECT COUNT(*) FROM rooms WHERE status = 'available'";
$result = @mysql_query($sql) or die("Could not execute query");

?> 
if(< ?php $result <= 14 ?>){
 alert("Rooms left: < ?php echo $result ?>");
 }

else{
 alert("Welcome Admin.");
 } 
}

window.onload=prompt;

编辑:

该代码现在工作正常,但它显示“资源 id#4”,而不是计数值。

4

5 回答 5

1

我觉得你不能将 php 与 js 代码混合使用。php主要在服务器端,而js是您提供的代码段的客户端,也许您应该使用纯php,如下所示:

< ?php 
    include("dbconfig.php");
    $sql = "SELECT COUNT(*) FROM rooms WHERE status = 'available'"; 
    $result = @mysql_query($sql) or die("Could not execute query");
    if ($result <= 14) {
        echo("Rooms left: $result");
    }
    else {
        echo("Welcome Admin.")
    }
 ?>

这应该在请求时首先运行

于 2010-10-14T05:56:43.253 回答
0

mysql_query返回资源,而不是结果。尝试使用:

$sql = "SELECT COUNT(*) FROM `rooms` WHERE `status` = 'available'";
$res = @mysql_query($sql) or die('Could not execute query');
$count = mysql_result($res, 0, 0);
于 2010-10-14T05:51:09.923 回答
0

php标签中不应有空格:

< ?php 
 ^

应该:

<?php 

您还缺少一个获取功能,以下是如何获取变量中的行数:

<?php $count = mysql_num_rows($result);?>

稍后您可以在条件中使用该$count变量。if

于 2010-10-14T05:51:47.547 回答
0

使用mysql_fetch_row,然后在条件中,比较 $row[0]

$sql = "SELECT COUNT(*) FROM `rooms` WHERE `status` = 'available'";
$res = @mysql_query($sql) or die('Could not execute query');

$row = mysql_fetch_row($res);

if(< ?php $row[0] <= 14 ?>){
于 2010-10-14T05:55:41.977 回答
0

我认为您对 PHP 处理位置与 Javascript 处理位置感到困惑。

PHP 在服务器端处理,而 Javascript 在客户端处理。像这样想...

  1. 您访问一个页面。
  2. 处理您的 PHP,并将最终输出发送到浏览器。
  3. 您的 Javascript 由浏览器处理。

正如你现在所拥有的那样,你会得到一些有趣的输出......尤其是因为你缺少echo语句。以下是您可能会在浏览器页面源代码中看到的内容:

function prompt()
{
if(){
 alert("Rooms left: < ?php echo $result ?>");
 }
else{
 alert("Welcome Admin.");
 } 
}

window.onload=prompt;

注意空的if 语句(也是开始标签中的空格:

if(<?php echo ($result <= 14); ?>){
 alert("Rooms left: <?php echo $result ?>");
 }

这应该使您的 Javascript 评估布尔值 true/false。不要忘记 Javascript 也需要包含在 <script> 标记中!

要回答您的 MySQL 问题... 试试这样:

//We can alias the COUNT(*) as MyCount for easy reference
$sql = "SELECT COUNT(*) as MyCount FROM rooms WHERE status = 'available'";
$result = @mysql_query($sql) or die("Could not execute query");
$row = mysql_fetch_array($result); //$row is now an array and will now have your count in it
echo $row['MyCount']; //This will print the count from the database. You could use it in other ways as well.
于 2010-10-14T05:59:07.137 回答