Results 1 to 5 of 5
  1. #1

    using placehandlers in PHP

    I don't program in PHP but I see a lot of posts here where people replace variables inside the query, instead of using placehandlers. I.e.:

    mysql_query("UPDATE writings SET titleofpiece='$newtitle' WHERE pieceid='$id'");

    This is extremely dangerous as most of the time variables are not checked and $id can be sth like

    1' or '0'='0

    which gets replaced like this:

    mysql_query("UPDATE writings SET titleofpiece='$newtitle' WHERE pieceid='1' or '0' ='0'");
    and all the rows are updated.

    Isn't there a simple way in PHP to use placehandlers? In Perl, using DBI, I would write the query like this:

    my $sth = $dbh->prepare("UPDATE writings SET titleofpiece = ? WHERE pieceid = ?");
    $sth->execute($newtitle, $id);

    What is the equivalent in PHP? I don't use PHP myself, but I wonder why this common mistake is in many of the PHP+Mysql posts.

  2. #2
    Join Date
    Aug 2000
    Sheffield, South Yorks
    Depends on what abstraction layer you use. PEAR:B, PEAR::MDB2 libs both support that. As does the PHP5 PDO library.
    Karl Austin :: KDA Web Services Ltd.
    UK Business Hosting and Managed Servers - Hosting for Business Users :: 0800 5429 764
    Call us today and ask about our hosting solutions.

  3. #3
    Edit -> the above post beat me.

  4. #4
    Just a side question - why not check variables by yourself instead of using an abstraction layer to do your work? Its not hard to do this:

    PHP Code:

    addslashes($newtitle); // or call custon string cleaning func.
    $id intval($id);

    mysql_query("UPDATE writings SET titleofpiece='$newtitle' WHERE pieceid='$id'"); 
    Programmers' lazyness leads to vunerabilities which lead to blaming a language to be insecure. I'm not attacking or accusing you but I'm just wondering..

    Anyway, abstraction layers are ok and all, but do you really need 100kb+ of php code just because you're not sanitizing your variables first?

  5. #5
    Join Date
    Aug 2002
    Compile your PHP with the MySQLi interface:

    $mysqli = new mysqli( 'localhost', 'user', 'password', 'data' );
    $stmt = $mysqli->prepare("UPDATE writings SET titleofpiece = ? WHERE pieceid = ?");
    $stmt->bind_param( 'si', $title, $pieceid ); 
    $title = 'A great book';
    $pieceid = 23;
    echo $stmt->affected_rows; 
    circlical - hosting software development
    forums * blog

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts