如何在html中查看数据库值

时间:2014-05-06 22:19:03

标签: javascript php html json database

我正在尝试可视化sql数据库。最后我希望看到某种图表,但我无法将值从php转换为js和html。在我的数据库中有两个来自同一表单的条目。第一个文件是一个php文件,我称之为“ read.php ”:

<?php
$con=mysqli_connect("localhost","root","password","databasename");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


$result = mysqli_query($con,"SELECT * FROM tablename");


while($row = mysqli_fetch_array($result)) {
    $data[] = array(
            'join_date' => $row['join_date'],
            'column1' => $row['column1'],
            'column2' => $row['column2'],
            'column3' => $row['column3'],
            'column4' => $row['column4']
          );
        echo json_encode($data);    
}
mysqli_close($con);
?>

当我打开这个文件时,我将其视为json。我想在html文件中看到这些列,所以我做了“ readjson.html ”:

<!DOCTYPE html>
<html>
<body>
<h2> Database in html</h2>

One: <p1 id="origname1"></p1><br>  
two: <span id="origname2"></span><br>  

<script type="text/javascript" > 
var baza = "<?php ($data )[http://localhost/read.php]; ?>";

document.getElementById("origname1").innerHTML=baza[0].join_date + ", " + baza[1].column1 + ", " + baza[0].column2 + ", " + baza[0].column3 + ", " + baza[0].column4;
document.getElementById("origname2").innerHTML=baza[1].join_date + ", " + baza[1].column1 + ", " + baza[1].column2 + ", " + baza[1].column3 + ", " + baza[1].column4;

</script>
</body>
</html>

当我打开readjson.html时,我看到了:

html中的数据库 一:未定义,未定义,未定义,未定义,未定义 二:未定义,未定义,未定义,未定义,未定义

我希望看到数据库条目,而不是 undefined 。请帮忙。

1 个答案:

答案 0 :(得分:0)

首先,我想知道你是怎么想到的:

"<?php ($data )[http://localhost/read.php]; ?>";

这不是PHP语法。您想要的是包含该文件,并在read.php中不打印json_encode

<?php
$con=mysqli_connect("localhost","root","password","databasename");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


$result = mysqli_query($con,"SELECT * FROM tablename");

$data = array();
while($row = mysqli_fetch_array($result)) {
    $data[] = array(
            'join_date' => $row['join_date'],
            'column1' => $row['column1'],
            'column2' => $row['column2'],
            'column3' => $row['column3'],
            'column4' => $row['column4']
          );
}
mysqli_close($con);
?>

然后包括它:

<?php
include 'read.php';
?>
<!DOCTYPE html>
<html>
<body>
<h2> Database in html</h2>

One: <p1 id="origname1"></p1><br>  
two: <span id="origname2"></span><br>  

<script type="text/javascript" > 
var baza = JSON.parse(<?php echo '"' . json_encode($data) . '"'; ?>);

document.getElementById("origname1").innerHTML=baza[0].join_date + ", " + baza[1].column1 + ", " + baza[0].column2 + ", " + baza[0].column3 + ", " + baza[0].column4;
document.getElementById("origname2").innerHTML=baza[1].join_date + ", " + baza[1].column1 + ", " + baza[1].column2 + ", " + baza[1].column3 + ", " + baza[1].column4;

</script>
</body>
</html>

我无法向您保证这会有效,但请尝试一下!