0

我想制作自己的 php 工具包,而不是使用众多框架之一,特别是因为它们遵循 MVC,这不是我现在要寻找的。我想从基础开始,并考虑到 OO,我想要一个简单的 php mysql 连接在一个单独的文件(config.php)中,查询在另一个文件(index.php)中

我试过这个,但它不工作。我究竟做错了什么?

根目录下的 config.php

<?php
$dsn = 'mysql:dbname=testdb;host=localhost';
$username = 'root';
$password = 'root';
$dbh = new PDO($dsn, $username, $password);
?>

根目录下的 index.php

<html>
<body>
<form action="" method="POST">
    <input type="text" name="search" autofocus />
    <input type="submit" value="search" />
</form>
</body>
</html>

<?php
require_once 'config.php';
$query = "SELECT * FROM table WHERE field = '" . $search . "'";
$results = mysql_query($query);
while($row = mysql_fetch_array($results)){ ?>
<li>
<?php echo $row['field']; ?>
</li>   
<?php } ?>

更新:请耐心等待,我对此的了解是新的。谢谢你。

4

3 回答 3

3

您正在混合mysql_*PDO...写下您的查询PDO并摆脱该mysql_*业务。

于 2013-05-14T19:59:00.630 回答
1

instead of

$query = "SELECT * FROM table WHERE field = '" . $search . "'";
$results = mysql_query($query);

use something like

$stmt = $dbh->prepare("SELECT * FROM table WHERE field = :search");
$params = array(':search' => $search);

$res = $stmt->execute($params);

$results = $res->fetchAll();
..
于 2013-05-14T20:03:53.830 回答
0

要确保包含您的 config.php 文件,只需在 index.php 中的 require 语句后打印出您的 $dbh 变量

require_once 'config.php';
print_r($dbh);

你应该从手柄上得到某种打印。

于 2013-05-14T21:25:18.697 回答