Jump to content

fetch multiple rows outside function


Balderick

Recommended Posts

 

Hi All,

I'm looking for a solution in using a function. The function fetches data from a database. In a column multiple results are found.

I want to have all the records outisde the function.

Inside the function all records are shown, but outside only the last record. I thought I could use return array, but it only returns multiple variables  and not multiple rows.

Not sure if fetch() is the solution for arrays.

 

example:

 


	<?php  


	 
	function test_func($val4) {
		
		global $val1;
		global $val2;
		global $val4;
		
		
		
		$servername = "host";
		$username = "johndoe";
		$password = "admin";
		$dbname = "dbase_db";

	// Create connection
	$conn = new mysqli($servername, $username, $password, $dbname);

	// Check connection
	if ($conn->connect_error) {
		die("Connection failed: " . $conn->connect_error);
	}


	//
	 
	if ($stmt = $conn->prepare("SELECT col1, col2 FROM table WHERE col4 = ? ;  ")) {

		$stmt->bind_param("s", $val4);
		$stmt->execute();
		$stmt->store_result();
		$num_of_rows = $stmt->num_rows;
		var_dump($num_of_rows);
		$stmt->bind_result($val1, $val2);
		
	 

		   if ($num_of_rows > 0){
			while ($stmt->fetch()) { 
	 
		// managed to output multiple rows here, but that's not the goal
		 
				
		 
				 
	}

	return array ($val1, $val2);

		   }
	}

	} 




	 $val4='form_value';
	 
	test_func($val4); 
	 
	 // return multiple rows here, outside the function
	 

 

How should I solve this?

Edited by Balderick
Link to comment
Share on other sites

1 hour ago, dsonesuk said:

Where ever you call the function, it should output the output from within the function, but depending on how the output is created, determines if the call of the function requires a echo.

why should the output be called from within the function?

 

 

Link to comment
Share on other sites

Never said call from within function, anywhere outside the function within body of page.

Depending on type of result you could simply concatenate the results then return.

Simplerfied example

 

$join="";

function dothis(){

for($i=0;$i<10;$i++){

$join.='Hello World '.$i.'<br>';

}

return $join;

}

Then anywhere in body echo the function

echo dothis();

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...