Page 1 of 1

Array values as function parameters

Posted: Mon Jun 19, 2006 10:28 am
by Maugrim_The_Reaper
Couldn't see how it was possible (maybe it's not!).

Say I have an array of values, where the count is not fixed - i.e. cannot use the number index for this one. I have a PHP function, like say mysqli_stmt_bind_param() which accepts an arbitrary number of variables to bind to a prepared statement. Is it possible to inject the array values into such a function through some wizardry or am I completely lost and need to fall back on a foreach loop?

Some example of what I mean. In attempting to hack an ExecuteStatement method for an abstraction class, I start building:

Code: Select all

function ExecuteStatement($statement, $inputarr) {
		if($inputarr)
		{
			// Better to bind them before now!
			$this->BindParameters($statement, $inputarr);
		}
		$resultID = mysqli_stmt_execute($statement);
	}

	function BindParameters($stmt, $inputarr) {
		$type = '';
		$params = array();
		foreach($inputarr as $param) {
			switch(gettype($param)){
				case 'string':
					$type .= 's';
					break;
				case 'integer':
					$type .= 'i';
					break;
				case 'double':
					$type .= 'd';
					break;
				case 'boolean':
					$param = $param ? 1 : 0;
					$type .= 'i';
					break;
				default:
					if ($param === null) {
						$param = 'NULL'; // how does one specify NULL for binding?
					}
					$type .= 's'; // binds an empty string rather than a NULL value (temp)
			}
			$params[] = $param;
		}
		mysqli_stmt_bind_param($stmt, $type, $params); // bad syntax I know...
	}
End result in theory (I know about the last syntax error - it's intentional) is to get $params into the function. mysql_stmt_bind_param() syntax is actually:

bool mysqli_stmt_bind_param ( mysqli_stmt stmt, string types, mixed &var1 [, mixed &...] )

Posted: Mon Jun 19, 2006 10:33 am
by feyd
call_user_func_array() should work just fine for this.

Posted: Mon Jun 19, 2006 10:36 am
by Maugrim_The_Reaper
I'm seriously thinking about memorising the manual...;)

Thanks!