I'm trying to write prepared statements for user input. The number of parameters changes based on user input. Oam is trying this code
PHP code:
$string = "my name"; $search_exploded = explode( " ", $string ); $num = count( $search_exploded ); $cart = array(); for ( $i = 1; $i <= $num; $i ++ ) { $cart[] = 's'; } $str = implode( '', $cart ); $inputArray[] = &$str; $j = count( $search_exploded ); for ( $i = 0; $i < $j; $i ++ ) { $inputArray[] = &$search_exploded[ $i ]; } print_r( $inputArray ); foreach ( $search_exploded as $search_each ) { $x ++; if ( $x == 1 ) { $construct .= "name LIKE %?%"; } else { $construct .= " or name LIKE %?%"; } } $query = "SELECT * FROM info WHERE $construct"; $stmt = mysqli_prepare( $conn, $query ); call_user_func_array( array( $stmt, 'bind_param' ), $inputArray ); if ( mysqli_stmt_execute( $stmt ) ) { $result = mysqli_stmt_get_result( $stmt ); if ( mysqli_num_rows( $result ) > 0 ) { echo $foundnum = mysqli_num_rows( $result ); while( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) { echo $id = $row['id']; echo $name = $row['name']; } } }
When I print_r($inputArray)
the output is:
Array ( [0] => ss [1] => my [2] => name )
No errors are shown in the error log.
What went wrong?
Write a generic query handler and pass it your query, parameter array, and parameter type list. Returns a set of results or messages. This is my own personal version of mysqli (I mostly use PDO, but have similar functionality set up for this). Do the same for inserts, updates, and deletes. Then just maintain your one library and use it for everything you do :) Note that if you start with this, you may want to handle connection errors etc. better.
%
Surround parameters, not placeholders.My code snippet will use object-oriented mysqli syntax, rather than the procedural syntax demonstrated by your code.
First you need to set up the necessary ingredients:
I will combine #2 and #3 into a variable for easier "unpacking" using the splat operator (
...
). The data type string must be the first element, then one or more elements will represent the bound value.As a logical inclusion, if there is no condition in the WHERE clause, there is no benefit to using a prepared statement; just query the table directly.
Code: (PHPize.online Demo)
For anyone looking for similar dynamic query techniques:
SELECT
,IN()
contains a dynamic number of valuesINSERT
One timeexecute()
The number of dynamic rows called