souper Posted February 25, 2011 Share Posted February 25, 2011 Heya, i'm a noob looking for some criticism on a bit of code that I wrote. I'm trying to form a function for updating records within a database. I've just recently learned about prepared statements so i'm trying to implement them into my existing code for security reasons. The problem that i'm having with using a function is that I have to pass the table names through variables which can't be used as a parameter for the PS. Therefore leaving me with the question: should I be using a function for this or should I just have multiple PS's throughout my code? Below is what I currently have running. Throughout my code I have arrays generated by forms: if( isset($_POST['edit']) ) { foreach( $_POST as $var => $value ) { $fields[] = $var; $vars[] = $value; } } Then I send the arrays to the function: update( database, table, $fields, $vars, field, null, null, $field, null, null, 'ORDER BY id', 'LIMIT 1', 1 ); Function: function update( $database, $table, $fields, $vars, $field1, $field2, $field3, $value1, $value2, $value3, $order, $limit, $num ) { $database = database( $database ); $table = table( $table ); $order = order( $order ); $limit = limit( $limit ); $num = intval( $num ); $db = new mysqli( 'localhost', '*', '*', $database ); $stmt = $db->stmt_init(); $arraySize = count( $fields ); for( $int = 0; $int < $arraySize; $int++ ) { if( checkInt( $fields[$int], $vars[$int] ) ) { $vars[$int] = intval( $vars[$int] ); $par1 = "i"; } else { $par1 = "s"; } if( $num == 1 ) { if( checkInt( $field1, $value1 ) ) { $value1 = intval( $value1 ); $par2 = "i"; } else { $par2 = "s"; } if( $vars[$int] != 'Submit' ) { $stmt->prepare( "UPDATE $table SET $fields[$int] = ? WHERE $field1 = ? $order $limit" ); $stmt->bind_param( "$par1$par2", $vars[$int], $value1 ); $stmt->execute(); } } } $stmt->close(); $db->close(); } I was told to hardcode all of the variables not being prepared. I'm not positive this is actually helpful though. Any input here would be appreciated. (i've done this for $database, $table, $order, $limit, $num: function table( $value ) { if( empty( $value ) ) { break; } else { $tables = array( 'comments', 'results' ); $key = array_search( $value, $tables ); return $tables[$key]; } } I guess i'm asking if this is OK or am I heading down the wrong direction. I hear using classes is a better solucion but i'm having trouble trying to understand how to use them. Any help would be appreciated, thanks! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.