jjacquay712 Posted September 7, 2008 Share Posted September 7, 2008 I am trying to make a php function that does an sql query, then assigns the result to a variable that is global in the script. Heres an example: <?php myfunction("My SQL Query", $the_variable_that_contains_my_query); echo $the_variable_that_contains_my_query; ?> how would i go about making such a function? Thanks, John Link to comment https://forums.phpfreaks.com/topic/123178-solved-php-query-function/ Share on other sites More sharing options...
genericnumber1 Posted September 7, 2008 Share Posted September 7, 2008 it's bad practice to assign values globally in a function. do function query($query) { return mysql_query($query); } $result = query($query); this function serves no purpose though, there's no reason not to just use mysql_query(). Link to comment https://forums.phpfreaks.com/topic/123178-solved-php-query-function/#findComment-636169 Share on other sites More sharing options...
DarkWater Posted September 7, 2008 Share Posted September 7, 2008 I wouldn't do this, but you could...Here's how: function do_query($query, &$result) { $result = mysql_query($query) or die(mysql_error()); } Whatever variable you pass into the function will be modified in the space in which it was declared. Link to comment https://forums.phpfreaks.com/topic/123178-solved-php-query-function/#findComment-636172 Share on other sites More sharing options...
jjacquay712 Posted September 7, 2008 Author Share Posted September 7, 2008 Im trying to make a function so my code will be less "dirty". hers what i usually do: $resource = mysql_query("blah blah blah") or die(""); $username = mysql_result($resource, 0, 'username'); but that takes up to much space, and if there's an error, it prints it on the page. with a function you could do a error_reporting(0); and suppress the error in only one part of the code. Link to comment https://forums.phpfreaks.com/topic/123178-solved-php-query-function/#findComment-636173 Share on other sites More sharing options...
DarkWater Posted September 7, 2008 Share Posted September 7, 2008 1) Never use mysql_result(). Ever. Honestly. 2) If there's an error on the page, you're doing it wrong. Don't suppress the error, handle it properly. Link to comment https://forums.phpfreaks.com/topic/123178-solved-php-query-function/#findComment-636175 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.