Jump to content

MySQL Query / Extract Function


besouza

Recommended Posts

Hello,

I'm trying to write a function that queries my MySQL server and extracts the data, then passes it along to the page calling for the function. Here's what I have so far... I can't seem to pass the variables along to the PHP script calling the function.

 

functions.php

function QueryServer($QueryName, $Query) {
	mysql_connect($MySQL_Server, $MySQL_Username, $MySQL_Password) or die(mysql_error()); 
	mysql_select_db($MySQL_Database) or die(mysql_error());

	$PerformQuery = mysql_query($Query) or die("ERROR! MySQL said".mysql_error());

	while ($QueryResult = mysql_fetch_assoc($PerformQuery)) {
		extract($QueryResult);
	}
}

 

calling to the function in functions.php

require_once "functions.php";
QueryServer('NewFieldSelect', 'SELECT * FROM checklist');
print $VariableWithinMySQL;

 

Any help is greatly appreciated  :D

Link to comment
https://forums.phpfreaks.com/topic/187449-mysql-query-extract-function/
Share on other sites

Ignoring the fact that the code doesn't really do what you're intending, there's probably another question you need to answer first.

 

Are your queries going to be returning a single row in the table every time?  You're going to have to set up an array to store these variables, as, if you just use extract(), the variable names are going to get overwritten and the only values available will be the final row produced by the query.

I think I figured it out...

 

function QueryServer($QueryName, $Query) {
	mysql_connect($MySQL_Server, $MySQL_Username, $MySQL_Password) or die(mysql_error()); 
	mysql_select_db($MySQL_Database) or die(mysql_error());

	$PerformQuery = mysql_query($Query) or die("ERROR! MySQL said".mysql_error());

	while ($QueryResult = mysql_fetch_assoc($PerformQuery)) {
		$GLOBALS['ResultArray'] = array($QueryResult[iD], $QueryResult[FieldName]);
	}
}

 

QueryServer('NewFieldSelect', 'SELECT * FROM fields');
	print_r ($ResultArray);

 

Thank again PHP Monkeh

Although that works fine you may want to shy away from using globals in your code, as if someone has globals switched off it won't work.

 

A better way to do it would be to specify a variable for the function to return a value to, for example:

 

<?php

function myFunction()
{
    $value = "Value from myFunction()";
    return $value;
}

$newVar = "Hello";
$newVar = myFunction();
echo $newVar // "Value from myFunction()" is printed

?>

 

This is a much better method than using globals, plus it gives you control over which variable gets the result of the function, whereas with your method it will always be $ResultArray that gets the value.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.