I am trying to write a function that will insert a new record using data from an array. I have most of the function written out except for the bind_param. Does anyone have any suggestions on how to finish this function or a better way of achieving the same thing?
// $valueArray could look like this...
// [0] => array('fieldName'=>'name_first', 'fieldValue'=>'Mike', 'fieldType'=>'s');
// [1] => array('fieldName'=>'name_last', 'fieldValue'=>'Jenkins', 'fieldType'=>'s');
// [2] => array('fieldName'=>'userid', 'fieldValue'=>'5016', 'fieldType'=>'i');
function addNewRecord($valueArray, $tableName){
$recordAdded = false;
$numOfValues = count($valueArray);
//first make sure some values were passed to this function so that we can create a record
if($numOfValues > 0){
//create question mark string and value type string
for($i=0, $i < $numOfValues, $i++){
if($i == 0){
$questionMarks = "?";
}else{
$questionMarks .= ", ?";
}
$valueTypes .= $valueArray[i]["fieldType"];
}
$statement = $this->connection->prepare("INSERT INTO $tableName VALUES ($questionMarks)");
$statement->bind_param($valueTypes, /***** any ideas on how do I handle this part *****/);
$recordAdded = $statement->execute();
}
return $recordAdded;
}
I used eval() to finish this function (*I have not tested this code). If any one has any tips or better work arounds I would love to hear them. Thanks!
// for this code update I no longer carry over the field names because they are not used in this function
// $valueArray could look like this...
// [0] => array('data'=>'Mike', 'type'=>'s');
// [1] => array('data'=>'Jenkins', 'type'=>'s');
// [2] => array('data'=>'5140', 'type'=>'i');
function addNewRecord($valueArray, $tableName){
$recordAdded = false;
$numOfValues = count($valueArray);
//first make sure some values were passed to this function so that we can create a record
if($numOfValues > 0){
$questionMarks = "?";
$dataValues = '$valueArray[0][\'data\']';
for($i=1; $i<$numOfValues; $i++){
$questionMarks .= ", ?";
$dataValues .= ', $valueArray['.$i.'][\'data\']';
$dataTypes .= $valueArray[$i]['type'];
}
$statement = $this->connection->prepare("INSERT INTO $tableName VALUES ($questionMarks)");
$bindingCommand = '$statement->bind_param("'.$dataTypes.'", '.$dataValues.');';
eval($bindingCommand);
$recordAdded = $statement->execute();
}
return $recordAdded;
}
Wouldn't it be easier to prepare the statement and return the mysqli_stmt object (or another wrapper)?
This way you could use the statement multiple times instead of creating it for each query - that's part of the advantages of prepared stamtents.
Wouldn't it be easier to prepare the statement and return the mysqli_stmt object (or another wrapper)?
This way you could use the statement multiple times instead of creating it for each query - that's part of the advantages of prepared stamtents.