使用一个连接(配置)显示数据,其他连接则不显示


With one connection (config) displays data, with other not

我正试图开发一个脚本,我在互联网上发现(搜索/自动建议)。脚本很小,但问题我认为是在连接,配置文件。我发现,旧的连接风格是正常工作的脚本,但如果我使用"定义"连接,那么所有的脚本停止工作,不显示任何数据。

<<p> 老连接/strong>
$host="aha";
$user="aha";
$pass="aha";
$base="aha";
$connect=mysql_connect($host,$user,$pass);
mysql_select_db($base, $connect);
?>

定义连接不能使用脚本

define("DB_HOST", "aha");
define("DB_NAME", "aha");
define("DB_USER", "aha");
define("DB_PASS", "aha");

我相信,这个脚本是用非常旧的代码写的,所以我猜,这个非常小的脚本应该用新的方式重写,但问题是,我应该如何正确地做到这一点?

脚本

<?php
include('config.php');
if($_POST)
{
$q=$_POST['searchword'];
$sql_res=mysql_query("select * from users where user_firstname like '%$q%' or user_lastname like '%$q%' order by user_id LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$fname=$row['user_firstname'];
$lname=$row['user_lastname'];
$email=$row['user_email'];
$re_fname='<b>'.$q.'</b>';
$re_lname='<b>'.$q.'</b>';
$final_fname = str_ireplace($q, $re_fname, $fname);
$final_lname = str_ireplace($q, $re_lname, $lname);

?>
<div class="display_box" align="left">
<a href="http://www.google.com/">
<img src="user_img/y.jpg" style="width:25px; float:left; margin-right:6px" /><?php echo $final_fname; ?>&nbsp;<?php echo $final_lname; ?><br/>
<span style="font-size:9px; color:#999999"><?php echo $email; ?></span>
</a>
</div>
<?php }} else {} ?>

我将感激任何帮助!

应该可以正常工作…只要你的config.php可以正确地引用变量(即,它们要么在该文件本身声明,要么在其他地方声明并包含在config.php文件中)。

config . php:

<?
define("DB_HOST", "aha");
define("DB_NAME", "aha");
define("DB_USER", "aha");
define("DB_PASS", "aha");
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME, $connect);
?>

在您的新连接配置中,您实际上并没有建立数据库连接,您只是定义常量。

有许多库抽象了数据库层来帮助你的代码更容易读,并自动完成转义等操作。您应该查看pdo http://php.net/manual/en/book.pdo.php