没有来自Localhost数据库的响应?

时间:2015-12-03 08:41:04

标签: php jquery html mysql

我不是专业编码员。我只是想创建自己的网站。我在下面执行了以下步骤,但它没有工作。

1 - 我在localhost数据库中为博客创建了类别。

http://i.hizliresim.com/3jqE3M.jpg

2 - 我创建了database.php,如下所示。

<?php 

mysql_connect("localhost","root",""); 

mysql_select_db("mycms"); 

?>

3 - 我将以下代码添加到home.html

<?php 
include("includes/database.php"); 

$get_cats = "select * from `categories`"; 

$run_categories = mysql_query($get_cats); 

while ($cats_row=mysql_fetch_array($run_cats)) { 

$cat_id=$cats_row['cat_id']; 
$cat_title=$cats_row['cat_title']; 

echo "<li><a href='home.html?cat=$cat_id'>$cat_title</a></li>"; 

} 

?> 

但是我无法看到http://localhost/MyCMS/home.html

中的类别

它没有用。问题是什么 ?我怎么解决这个问题。请帮帮我:(

2 个答案:

答案 0 :(得分:1)

home.html更改为home.php,因为具有.html扩展名的html页面无法执行PHP代码。还有一件事,mysql_*将来会弃用,请改用mysqli_*pdo。在while循环中,必须确保传递$run_categories而不是$get_cats,如下面的代码:

// this variable only store string, not the query itself
$get_cats = "select * from `categories`";
$run_categories = mysql_query($get_cats); 

while ($cats_row=mysql_fetch_array($run_categories)) {...}

建议使用以下任一版本之一:

1)Mysqli版本

<?php 
// database connection
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con, "mycms");

$get_cats = "select * from `categories`";
$run_categories = mysqli_query($con, $get_cats); 

while ($cats_row=mysqli_fetch_array($run_categories )) { 

 $cat_id=$cats_row['cat_id']; 
 $cat_title=$cats_row['cat_title'];
 echo "<li><a href='home.html?cat=$cat_id'>$cat_title</a></li>";

} 
?>

2)PDO版本

<?php 
// database connection
$con = new PDO('mysql:host=localhost;dbname=mycms;charset=utf8', 'root', '');
$get_cats = "select * from `categories`";
$run_categories = $con->query($get_cats); 

while ($cats_row = $run_categories->fetch(PDO::FETCH_ASSOC)) { 

 $cat_id=$cats_row['cat_id']; 
 $cat_title=$cats_row['cat_title'];
 echo "<li><a href='home.html?cat=$cat_id'>$cat_title</a></li>";

} 
?>

答案 1 :(得分:1)

只有在文件名的扩展名为.php时才会执行第一个PHP代码,因此将home.html更改为home.php

其次,您的代码中也有一个小错误。

<?php 
include("includes/database.php"); 

$get_cats = "select * from `categories`"; 

$run_categories = mysql_query($get_cats); 

//while ($cats_row=mysql_fetch_array($run_cats)) { 

// The parameter to mysql_fetch_array should be 
// the result of a call to mysql_query()
while ($cats_row=mysql_fetch_array($run_categories )) { 

    $cat_id=$cats_row['cat_id']; 
    $cat_title=$cats_row['cat_title']; 

    echo "<li><a href='home.html?cat=$cat_id'>$cat_title</a></li>"; 
} 
?> 

另外

  

请不要使用mysql_数据库扩展,不推荐使用(在PHP7中永远消失)   特别是如果您只是学习PHP,请花时间学习PDOmysqli_数据库扩展,   and here is some help to decide which to use

相关问题