mysqli_stmt_bind to all fields in a query?

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
Cody Mays
Forum Newbie
Posts: 10
Joined: Fri Dec 15, 2006 3:01 pm

mysqli_stmt_bind to all fields in a query?

Post by Cody Mays »

I'm trying the method used to bind to all fields that's in the comments here: http://www.php.net/manual/en/function.m ... result.php (3rd comment down) but I get NULL on the &$array[$field->name]; part according to var_dump.

Var dump output:

Code: Select all

array(9) { [0]=>  &object(mysqli_stmt)#10 (0) { } [1]=>  &NULL [2]=>  &NULL [3]=>  &NULL [4]=>  &NULL [5]=>  &NULL [6]=>  &NULL [7]=>  &NULL [8]=>  &NULL }
Code:

Code: Select all

	public function prep_bind_to_all(&$stmt)
	{
		$data = mysqli_stmt_result_metadata($stmt);
		$count = 1; //start the count from 1. First value has to be a reference to the stmt. because bind_param requires the link to $stmt as the first param.
		$fieldnames[0] = &$stmt;
		
		while ($field = mysqli_fetch_field($data))
		{
			echo($field->name.'<br />');
			$fieldnames[$count] = &$array[$field->name]; //load the fieldnames into an array.
			$count++;
		}
		
		var_dump($fieldnames);
		call_user_func_array(mysqli_stmt_bind_result, $fieldnames);
	}
Any ideas?
Cody Mays
Forum Newbie
Posts: 10
Joined: Fri Dec 15, 2006 3:01 pm

Post by Cody Mays »

I have gotten it to work now. I was misunderstanding how it should work.
Here is some code that works:

Code: Select all

	public function prep_bind_to_all(&$stmt)
	{
		$meta = mysqli_stmt_result_metadata($stmt);

		$keys = array();
		foreach(mysqli_fetch_fields($meta) as $col)
		{
			$keys[] = $col->name;
		}

		$values = array_fill(0, count($keys), NULL);
		
		/* Prepare array for calling */
		$refs = array();
		foreach($values as $i => &$f)
		{
			$refs[$i] = &$f;
		}
		
		call_user_func_array(array($stmt, 'bind_result'), $values);
		return array_combine($keys, $values);
	}
Post Reply