我的php脚本没有使用给定的用户名/ pass / host而是使用root @ localhost(密码:NO)

时间:2012-12-11 08:48:19

标签: php mysql connection

遇到了问题!虽然我发现几乎相似的线程但没有帮助:(

我写了一个php脚本来从我的MySQL数据库中获取注册用户的数量。该脚本在我的localhost中运行良好;它分别使用给定的用户名,传递和主机名,分别是“root”,“root”和“localhost”,但脚本没有使用给定的用户名/ pass / host,而是使用root @ localhost(密码:NO)在Live服务器中。

在Live服务器中,我创建了一个MySQL用户,设置了不同的密码,主机名当然不是localhost。我用新创建的mysql用户数据更新了脚本。但是,每当我运行脚本时,我都会看到脚本仍在使用“root”,“root”和“localhost”!!

看一下脚本:

    //database connection
    $conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
$db = mysql_select_db ("regdb",$conn); //Oops, actually it was written this way in the script. I misstyped it previously. now edited as it is in the script.

    //Query to fetch data
$query = mysql_query("SELECT * FROM regd ");            
while ($row = mysql_fetch_array($query)): 
$total_regd = $row['total_regd'];
endwhile;   

echo $total_regd;

- 有人说更改默认用户名并传入位于phpMyAdmin目录中的config.ini.php文件。这会有帮助吗?我没有尝试这个,因为我的托管服务提供商没有授予我访问该目录的权限(因为我使用免费托管来测试脚本)或者我根本找不到它:(

请帮忙......

2 个答案:

答案 0 :(得分:4)

前言:MySQL扩展标记为已弃用,最好使用mysqli或PDO


虽然您将连接资源存储在$ conn中,但是您没有在调用mysql_query()时使用它,并且您没有检查mysql_connect()的返回值,即如果连接由于某种原因而失败mysql_query() “是免费的”建立新的默认连接。

<?php
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
if ( !$conn ) {
    die(mysql_error()); // or a more sophisticated error handling....
}

$db = mysql_select_db ("regdb", $conn);
if ( !$db ) {
    die(mysql_error($conn)); // or a more sophisticated error handling....
}

//Query to fetch data
$query = mysql_query("SELECT * FROM regd ", $conn);
if (!$query) {
    die(mysql_error($conn)); // or a more sophisticated error handling....
}

while ( false!=($row=mysql_fetch_array($query)) ): 
    $total_regd = $row['total_regd'];
endwhile;   

echo $total_regd;


编辑:看起来你只处理了一行 要么将echo行移动到while循环中,要么(如果你真的只想要一条记录)在sql语句中更好地说出来并摆脱循环,例如

// Query to fetch data
// make it "easier" for the MySQL server by limiting the result set to one record
$query = mysql_query("SELECT * FROM regd LIMIT 1", $conn);
if (!$query) {
    die(mysql_error($conn)); // or a more sophisticated error handling....
}

// fetch data and output
$row=mysql_fetch_array($query);
if ( !$row ) {
    echo 'no record found';
}
else {
    echo htmlspecialchars($row['total_regd']);
}

答案 1 :(得分:1)

首先:

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}

你的mysql_error()是什么? :)