Search code examples
phpmysqlsql-injection

PHP sql Injection and custom numbers of parameters in function


Good day everyone: I'd like to parametrize my queries, creating a function that receive my query, connection and array with parameters expressed as "?". My function is:

receiveQuery($query, $mysqli1, $array1)

I have read about sql injection I would like to know that if this is a proper way to avoid these. I am planning to use this this function for INSERT, DELETE, UPDATE and SELECT. Also I would like you to guide me how could I create some better handling for more than 1 parameter, because currently I am using a switch. But every time I require more parameters, I am increasing the switch and I would like to create it dinamically.

SWITCH ($array1Length)

Any comments is helpful, regards. Felipe

<?php
    $mysqli1 = openConn();
    $query = "INSERT INTO tblTest (field1 , field2 ) VALUES (?,?)";
    $array1 =                array($value1, $value2);
    $result = receiveQuery($query, $mysqli1, $array1);
    if($stmt->affected_rows == 1)
    {
        $success = "Success.";
    }
    if($stmt->affected_rows == -1)
    {
        $error = "Error.";
    }
    closeConn($stmt);
    closeConn($mysqli1);

    function openConn()
    {
        $mysqli1 = new mysqli('localhost', 'userTest', '123', 'dbTest');
        if ($mysqli1->connect_error) {
            die('Connect Error (' . $mysqli1->connect_errno . ') '
                    . $mysqli1->connect_error);
        }
        return $mysqli1;
    }

    function receiveQuery($query, $mysqli1, $array1)
    {
        global $stmt;
        $stmt = $mysqli1->prepare($query);
        if (false===$stmt)
        {
            echo $mysqli1->error;
            die('Error');
        }
        $array1Length = count($array1);
        SWITCH ($array1Length)
        {
            CASE   0: break;
            CASE   1: $stmt->bind_param("s"   , $array1[0])                                 ;break;
            CASE   2: $stmt->bind_param("ss"  , $array1[0],$array1[1])                      ;break;
            CASE   3: $stmt->bind_param("sss" , $array1[0],$array1[1],$array1[2])           ;break;
            CASE   4: $stmt->bind_param("ssss", $array1[0],$array1[1],$array1[2],$array1[3]);break;
            DEFAULT : echo "Error";
        }
        $stmt->execute();
        $result = $stmt->get_result();

        return $result;
    }

    function closeConn($mysqli1)
    {
        $mysqli1->close();
    }

?>

Solution

  • You should be able to use the splat operator on your array.

    $s = '';
    for ($x = 0; $x < count($params); $x ++) {
        $s .= 's';
    }
    
    $stmt->bind_param($s, ...$params);
    

    https://secure.php.net/manual/en/migration56.new-features.php