简体   繁体   English

将mysql函数转换为pdo

[英]Convert mysql functions to pdo

How can I convert my MySQL functions to PDO? 如何将MySQL函数转换为PDO? I have successfully connected to my DB with the PDO call, but my scripts are still using the MySQL functions. 我已经通过PDO调用成功连接到数据库,但是我的脚本仍在使用MySQL函数。

function query_basic($query)
{
    $result = mysql_query($query);
    if ($result == FALSE)
    {
        $msg = 'Invalid query : '.mysql_error()."\n";
        echo $msg;
    }
}

function query_numrows($query)
{
    $result = mysql_query($query);
    if ($result == FALSE)
    {
        $msg = 'Invalid query : '.mysql_error()."\n";
        echo $msg;
    }
    return (mysql_num_rows($result));
}

function query_fetch_assoc($query)
{
    $result = mysql_query($query);
    if ($result == FALSE)
    {
        $msg = 'Invalid query : '.mysql_error()."\n";
        echo $msg;
    }
    return (mysql_fetch_assoc($result));
}

You forgot a semicolon after: 您在以下情况后忘记了分号:

$clientid = mysql_real_escape_string($_GET['id'])

Correct: 正确:

$clientid = mysql_real_escape_string($_GET['id']);
                                                 ^

The cause of these errors is that you're calling mysql_real_escape_string() before you've opened the connection to the database. 这些错误的原因是,在打开与数据库的连接之前,您正在调用mysql_real_escape_string()

mysql_real_escape_string() needs to be called after the DB connection has been established because it needs to know what the encoding scheme is for the database it's escaping for, so it knows what characters need to be escaped. 建立数据库连接后,需要调用mysql_real_escape_string() ,因为它需要知道要转义的数据库的编码方案是什么,因此它知道需要转义哪些字符。

Ideally, you should call it immediately before creating the SQL string; 理想情况下,您应该在创建SQL字符串之前立即调用它; escaped strings should be used only in the context that they have been escaped for, so you don't want them hanging around the program too far away from where the queries are built. 转义的字符串仅应在已转义的上下文中使用,因此,您不希望它们在程序中与查询的生成位置相距太远。 (This applies to all kinds of escaping, not just SQL). (这适用于各种转义,而不仅仅是SQL)。

Ultimately, you would be much better off if you switch to using a more modern database API such as PDO. 最终,如果您切换到使用更现代的数据库API(例如PDO),将会更好。 You still need to take care to avoid injection attacks, no matter what DB API you're using, but it's a lot easier with PDO. 无论使用哪种DB API,您都仍然需要小心避免注入攻击,但是使用PDO会容易得多。

A good tutorial for PDO can be found here: http://www.sitepoint.com/avoid-the-original-mysql-extension-2/ 可以在这里找到有关PDO的很好的教程: http : //www.sitepoint.com/avoid-the-original-mysql-extension-2/

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM