dynamic prepared insert statement

南笙酒味 提交于 2019-12-23 05:29:12

问题


Let me preface that I just started learning prepared statements so much of this might just be to much to grasp, but I want to try.

I am trying to make a dynamic create function within my DatabaseObject class. The function would take any number of values of potentially any number of the different allowed data types. Unfortunately nothing I have tried has worked. Here is the code.

public function create() {
    $db = Database::getInstance();
    $mysqli = $db->getConnection();
    //array of escaped values of all types in the object
    $attributes = $this->sanitized_attributes();

    $check = $mysqli->stmt_init();

    $paramType = array();

    $types = ''; $bindParam = array(); $where = ''; $count = 0;

    foreach($attributes as $key=>$val)
    {
        $types .= 'i';
        $bindParam[] = '$p'.$count.'=$param["'.$key.'"]'; 
        $where .= "$key = ? AND ";
        $count++;
    }

    $sql_query = "INSERT INTO `".static::$table_name."` ";  

    $sql_query .= "VALUES (";

    foreach ($attributes as $key => $value) {
        $valueType = gettype($value);

        if ($valueType == 'string') {
            $sql_query .= "?,";
            array_push($paramType, "s");
        } else if ($valueType == 'integer') {
            $sql_query .= "?,";
            array_push($paramType, "i");
        } else if ($valueType == 'double') {
            $sql_query .= "?,";
            array_push($paramType, "d");
        } else {
            $sql_query .= "?,";
            array_push($paramType, "b");
        }           
    }

    $sql_query .= ")";
}

At this point I am completely lost as to what I am suppose to do.

I have gotten simple prepared statements to work, but this one is much more complicated and dynamic and I don't know if I handled the process up to this point correctly and what to do following the sql_query in order to get this to work. All the questions here have left me confused so maybe if I got guidance with my current code to see where i went wrong it will assist.

I appreciate your time.


回答1:


public function create() {
    $db = Database::getInstance();
    $mysqli = $db->getConnection();

    $attributes = $this->sanitized_attributes();

    $tableName = static::$table_name;

    $columnNames = array();
    $placeHolders = array();
    $values = array();

    foreach($attributes as $key=>$val)
    {
        // skip identity field
        if ($key == static::$identity)
            continue;
        $columnNames[] = '`' . $key. '`';
        $placeHolders[] = '?';
        $values[] = $val;
    }

    $sql = "Insert into `{$tableName}` (" . join(',', $columnNames) . ") VALUES (" . join(',', $placeHolders) . ")";

    $statement = $mysqli->stmt_init();
    if (!$statement->prepare($sql)) {
        die("Error message: " . $mysqli->error);
        return;
    }

    $bindString = array();
    $bindValues = array();

    // build bind mapping (ssdib) as an array
    foreach($values as $value) {
        $valueType = gettype($value);

        if ($valueType == 'string') {
            $bindString[] = 's';
        } else if ($valueType == 'integer') {
            $bindString[] = 'i';
        } else if ($valueType == 'double') {
            $bindString[] = 'd';
        } else {
            $bindString[] = 'b';
        }

        $bindValues[] = $value;
    }

    // prepend the bind mapping (ssdib) to the beginning of the array
    array_unshift($bindValues, join('', $bindString));

    // convert the array to an array of references
    $bindReferences = array();
    foreach($bindValues as $k => $v) {
        $bindReferences[$k] = &$bindValues[$k];
    }

    // call the bind_param function passing the array of referenced values
    call_user_func_array(array($statement, "bind_param"), $bindReferences);

    $statement->execute();  
    $statement->close();

    return true;
}

I want to make special note that I did not find the solution myself. I had a long time developer find this solution and wanted to post it for those that might want to know.




回答2:


I accidently found your old post as I was trying myself to find a solution to the exact same problem. My code seems a bit more advantagous as there is only one loop included. Therefore I will add it as a possible improvement to this post:

    $sqlquery = $this->MySQLiObj->prepare($dummy);

    $paramQuery = array();
    $paramQuery[0] = '';

    $n = count($valueArray);
    for($i = 0; $i < $n; $i++) {
        $checkedDataType = $this->returnDataType($valueArray[$i]);
        if($checkedkDataType==false) {
            return false;
        }
        $paramQuery[0] .= $checkedDataType;
        /* with call_user_func_array, array params must be passed by reference -> & */
    $paramQuery[] = &$valueArray[$i];
    }

    /*In array(): sqlquery(object)->bind_param(method)*/
    call_user_func_array(array($sqlquery, 'bind_param'), $paramQuery);
    $sqlquery->execute();
    /*Can be used identical to $result = $mysqli->query()*/
    $result = $this->MySQLiObj->get_result();
    $sqlquery->close();

Utilizing the function returnDataType() with a switch statement, which might be faster if there is a preference for a certain data type.

    private function returnDataType($input) {
    switch(gettype($input)) {
        case string: return 's';
        case double: return 'd';
        case integer: return 'i';
        default: $this->LOG->doLog("Unknown datatype during database access."); return 's';
    }
}


来源:https://stackoverflow.com/questions/30358874/dynamic-prepared-insert-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!