简体   繁体   中英

Convert mysql functions to pdo

How can I convert my MySQL functions to PDO? I have successfully connected to my DB with the PDO call, but my scripts are still using the MySQL functions.

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() 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.

Ideally, you should call it immediately before creating the SQL string; 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).

Ultimately, you would be much better off if you switch to using a more modern database API such as 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.

A good tutorial for PDO can be found here: http://www.sitepoint.com/avoid-the-original-mysql-extension-2/

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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