如何使用PHP

时间:2016-01-06 21:04:28

标签: php

我想从数据库中获取数据并使用contacts.php文件在表中显示它们。我在几个文件中分离了项目,我的代码中有一个错误。这是我的代码: -
index.php

<html>
<head><meta charset="UTF-8">
</head>
<body>
<?php
require_once 'controller/ContactsController.php';
$controller = new ContactsController();
$controller -> listContacts();
?>
</body></html>

2.ContactsController.php

<?
require_once 'model/ContactsServices.php';
class ContactsController {
public function __construct() {
    $this->contactsService = new ContactsService();
}
public function listContacts() {
    //get all the details using : getAllContacts();
    $list1 = $this->contactsService-> getAllContacts();
    include 'view/contacts.php';
}
}

3.ContactServices.php

<?
require_once 'model/ContactsGateway.php';
class ContactsService {
public function __construct () {
    $this->contactsGateway = new ContactsGateway();
}
private function openDb() {
    //Connection to the data base
    $username = "root";
    $password = "";
    $database = "contacts";
    $server = "localhost";
    $conn = mysql_connect($server, $username, $password);
    if(!$conn){
        die("could not connect: ". mysql_error());
    }
    //select database
    $select_Db = mysql_select_db($database, $conn); 
}
private function closeDb() {
    //close the data base
    mysql_close($conn);
}
public function getAllContacts() {
    //open database
    $this->openDb();
    //select all detail :: selectAll(....);
    $list = $this->contactsGateway->selectAll();
}
}
?>

4.ContctsGateway.php

   <?
    class ContactsGateway {
    public function selectAll() {
        //query to get the detail
        $sql =  mysql_query("SELECT * FROM list");
    }
    }
    ?>

5.Contacts.php

<table border = "1">
<thead>
<tr>
    <td>Name</td>
    <td>Phone</td>
    <td>Email</td>
    <td>Address</td>
</tr>
</thead>
<tbody>
<?php
require_once 'model/ContactsServices.php';
$service = new ContactsService();
$service -> getAllContacts();
    $name = 'Name';
    $phone = 'Phone';
    $add = 'Address';
    $email = 'Email';
    while($rows = mysql_fetch_assoc($sql)){echo 3;
        echo
        "<tr>
            <td>{$rows['name']}</td>
            <td>{$rows['phone']}</td>
            <td>{$rows['email']}</td>
            <td>{$rows['add']}</td>
        </tr>\n";       
    }       
?>
</tbody>
</table>

当我尝试这段代码时,它只给表头带有错误。在contacts.php文件中错误地说$ sql变量是未定义的。我已经在contactsGateway.php中定义并继承到contacts.php。这是什么原因,有没有其他方法可以做到这一点?

1 个答案:

答案 0 :(得分:3)

您的SQL查询似乎无效。

SELECT * list

应该是:

SELECT * FROM list

此外,如果使用直接MySQL函数(从PHP 5.5开始不推荐使用,并在PHP 7中删除,顺便说一句),如果{{1}的结果,您可以使用mysql_error() } funciton等于-1。

例如:

mysql_query()

将在出错时停止脚本,并显示mysql错误信息。