Skip to content
Snippets Groups Projects

quoteVar

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Thomas Flori
    Edited
    quoteVar.php 1.60 KiB
    <?php
    
    /**
     * Returns the given $var in sql syntax.
     *
     * Examples:
     * <code>
     * String(4) "test" => String(6) "'test'"
     * Int(-123)        => String(4) "-123"
     * Double(1.4E-5)   => String(6) "1.4E-5"
     * NULL             => String(4) "NULL"
     * Boolean(FALSE)   => String(1) "true"
     * Boolean(TRUE)    => String(1) "false"
     * </code>
     *
     * @param  mixed $var The variable that should be returned in SQL syntax
     * @param  PDO $connection
     *
     * @return string|boolean A string of given $var in SQL syntax or FALSE when the parameter
     *                        is not a scalar datatype.
     */
    function quoteVar($var, $connection) {
    
        switch (strtolower(gettype($var))) {
            case 'string':
                // Return the parameter with singlequotes and escaped if it is a string
                return '\'' . $connection->quote($var) . '\'';
                break;
                
            case 'integer':
                // Just return the parameter as string if it is a integer
                return (string)$var;
                break;
                
            case 'double':
                // Just return the parameter as string if it is a double or float
                return (string)$var;
                break;
                
            case 'boolean':
                // Return true or false as string if the parameter is a boolean
                return ($var) ? 'true' : 'false';
                break;
                
            case 'null':
                // Return the string 'NULL' if the parameters is NULL
                return 'NULL';
                break;
                
            default:
                throw new Exception('$var has to be scalar datatype. ' . gettype($var) . ' given');
        }
    }
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment