Hello, CR :)
I've finally finished my universal query preparation function. Sorry about my previous post, I wasn't aware of the rules before.
Anyway, here is a working function. Any suggestions to make it better? I feel it could use some tweaking, but am not sure how I would go about it...
Variable examples/explanation
- $db | the database connection
- $query | ex) $query = "SELECT * FROM users WHERE
username=?" - $operation | The operation you wish to perform (number of rows, insert data)
- $type | the variable types in mysqli_stmt_bind_param (example: $type = "ssi")
$variables | the variables to replace the question marks with
function manipulate($db, $query, $operation, $type, $variables) { //Check Number of Variables inputted $numVars = (int)strlen($type); //Seperate variables into an array $var = explode(",",$variables); //Handle Statement $stmt = mysqli_stmt_init($db); if(mysqli_stmt_prepare($stmt, $query)) { echo "<br /> QUERY PREPARED <br />"; $x = 0; if( $numVars == 1 ) { mysqli_stmt_bind_param($stmt, $type, $var[0]); } else if ( $numVars == 2 ) { mysqli_stmt_bind_param($stmt, $type, $var[0], $var[1]); } else if ( $numVars == 3 ) { mysqli_stmt_bind_param($stmt, $type, $var[0], $var[1], $var[2]); } else if ( $numVars == 4 ) { mysqli_stmt_bind_param($stmt, $type, $var[0], $var[1], $var[2], $var[3]); } else if ( $numVars == 5 ) { mysqli_stmt_bind_param($stmt, $type, $var[0], $var[1], $var[2], $var[3], $var[4]); } mysqli_stmt_execute($stmt); mysqli_stmt_store_result($stmt); if($operation == "numRows" || $operation == "num_rows") { $output = mysqli_stmt_num_rows($stmt); } else { echo "Operation not supported"; } mysqli_stmt_close($stmt); return $output; } else { echo mysqli_stmt_error($stmt); echo "<br /> QUERY DENIED <br />"; } }
