我该如何解决这个错误? [function.mysql实时逃逸字符串]

时间:2013-07-27 10:29:31

标签: php mysql

我使用此代码:

<?php
    // Get values from form
    $name= mysql_real_escape_string($_POST['name']);
    if (empty($name)) {
        echo "No information has entered";
        echo "<br/>";
        echo "<br/>";
        echo "<a href='index.php'>Return to Homepage</a>";
        exit;
    }

    $host="localhost"; // Host name
    $username="root"; // Mysql username
    $password=""; // Mysql password
    $db_name="pin"; // Database name
    $tbl_name="test"; // Table name

    // Connect to server and select database.
        mysql_connect("$host", "$username", "$password")or die("cannot connect");
        mysql_select_db("$db_name")or die("cannot select DB");

            // Insert data into mysql
            $sql = "UPDATE $tbl_name SET `Used` = '1' WHERE `test`.`Code` =$name;";
            //echo $sql; exit;
            $result=mysql_query($sql);

            // if successfully insert data into database, displays message "Successful".
            if($result){
                echo "Your Information </br>";
                echo "<BR>";
                echo "<a href='index.html'></a>";
                $result = mysql_query("SELECT Code FROM `test` WHERE  `Code` =$name" );
                    while ($row = mysql_fetch_array($result)) {
                            printf("Code: %s </br>", $row[0]); 
                                $foundcode=$row[0];
                    }
                    if (!empty($foundcode)) {
                        echo "<BR>";
                        echo "<a href='".$foundcode.".pdf'>Click here to download.</a>";
                    }
                        if (empty($foundcode)){
                        echo "<BR>";
                        echo "Password is wrong";
                        }
                        mysql_free_result($result);
                echo "<BR>";
                echo "<BR>";
                echo "<BR>";
                echo "<a href='index.php'>Exit</a>";
            }

            else {
                echo nl2br ("Entered Information are not valid, Please enter valid information </br></br>");
                echo "<a href='index.php'>Return to Homepage</a></br></br>";
            }

        // close connection
        mysql_close();
?>

但是我收到了这个错误:

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'root'@'localhost' (using password: NO)

我读了一些帮助,但我无法修复它。 我读了一些关于这个问题的答案,如:

  1. Fatal error: Call to a member function prepare() on a non-object in PHP Call to a member function prepare() on a non-object error Fatal error: Call to a member function prepare() on a non-object with PDO
  2. 虽然我更改了数据库用户和通过,但问题仍然存在。

1 个答案:

答案 0 :(得分:0)

mysql_real_escape_string()需要数据库连接,因为应该进行转义的方式取决于连接参数。

PHP的MySQL扩展尝试创建数据库连接(如果需要)并且找不到可以使用的数据库连接。因此错误信息。

mysql_real_escape_string()之后致电mysql_connect()