通过HTML按钮显示SQL查询

时间:2017-04-09 22:05:30

标签: php html mysql

如果这是多余的,我道歉,我搜索了相关主题,但无法找到任何答案。我希望对我创建的数据库运行SQL查询,并在HTML按钮单击上显示结果。我从一个简单的场景开始,我只是从我的"客户"中选择所有实体。表。我创建了以下PHP代码来完成此任务:

<?php
define('DB_NAME', 'mis630db');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');

$link = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) {
        die('Could not connect:  ' . mysql_error());
}

$db_selected = mysql_select_db(DB_NAME, $link);

if (!$db_selected) {
        die('Can\'t use ' . DB_NAME . ':  ' . mysql_error());
}

$resultset = mysql_query("SELECT * FROM Customer");
if($resultset->num_rows !=0) {
    while($rows = $resultset->fetch_assoc())
    {
        $idCustomer = $rows['idCustomer'];
        $CustomerFName = $rows['CustomerFName'];
        $CustomerLName = $rows['CustomerLName'];
        $CustomerAddress = $rows['CustomerAddress'];
        $CustomerPhone = $rows['CustomerPhone'];
        $CustomerEmail = $rows['CustomerEmail'];

        echo"<p> Customer ID: $idCustomer<br />Customer Name:  $CustomerFName $CustomerLName<br />Customer Address:  $CustomerAddress<br />Customer Phone:  $CustomerPhone<br />Customer Email:  $CustomerEmail</p>";
    }
}   
else{
        echo "No results.";
}
?>

当我测试我收到此错误时:

&#34; 注意:尝试在第20行的C:\ xampp \ htdocs \ report.php中获取非对象的属性 没有结果。&#34;

我不确定为什么它应该返回多个结果。一旦整理完毕,我想将其连接到HTML按钮以显示结果,我将在其中创建一些按钮来运行我创建的各种SQL查询:

<html>
<head>
    <title> Reports</title>
</head>
<body>
<div class="header">
    <h1>Reports</h1>
</div>
<form action="report.php" method="post" />
    <table>
    <tr>
        <td><input type="submit" value="Customers" /><td>
    </tr>
</form>
</body>
</html>

非常感谢任何见解。

感谢。

2 个答案:

答案 0 :(得分:1)

看起来SQL查询SELECT * FROM Customer失败,因此$resultset不是对象 - 可能是null

SQL表,列等区分大小写。您确定您的表名为Customer而不是customer吗?

请注意,扩展名mysql自PHP 5.5起已弃用,并已在PHP 7中删除。您应该使用mysqliPDO-MySQL代替。

答案 1 :(得分:1)

更改此行:

if($resultset->num_rows !=0) {

if (mysql_num_rows($resultset) != 0) {

因为我认为你不能直接从mysql结果对象访问一个名为num_rows的方法。

并更改此行:

while($rows = $resultset->fetch_assoc())

while($rows = mysql_fetch_assoc($resultset))

因为我认为你不能直接从mysql结果对象访问一个名为fetch_assoc的方法。

还有另一件事。不推荐使用Mysql_函数我建议您开始使用mysqli_函数。 http://php.net/manual/en/book.mysqli.php