Is there a better, more “Standard” way to perform SQL queries in PHP without using a framework?

前端 未结 8 983
借酒劲吻你
借酒劲吻你 2021-01-27 09:02

For the longest time, I\'ve been using the following basic formatting for SQL queries within my PHP:

$sql = \"SELECT * FROM `user-data` WHERE `id` = \'\".$id.\"\         


        
8条回答
  •  清歌不尽
    2021-01-27 09:26

    I've been wondering why I am always seeing the more complicated form of string building like this: "literal string " . $a . " more literal", rather than "literal string $a more literal", or in your case:

    "SELECT * FROM `user-data` WHERE `id` = '".$id."' LIMIT 1;";
    

    instead of this:

    "SELECT * FROM `user-data` WHERE `id` = '$id' LIMIT 1;";
    

    For more complicated expressions, I like to use sprintf (but I was a c programmer for a long time):

    $sql = sprintf("SELECT * FROM `user-data` WHERE `id` = '%s' LIMIT 1", $id);
    

    This can also be written in this format:

    $sql = sprintf("
        SELECT * 
           FROM `user-data` 
        WHERE `id` = '%s' 
            LIMIT 1", 
        $id);
    

    In this case, it doesn't buy much, but when there are several variables embedded in the string, it makes it easier to manage.

提交回复
热议问题