PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Hi, I wrote a function to handle mysql queries, thing is, some times it works and sometimes not (it doesn't return anything, even though the sql is legal), and I can't figure out why!
here it is:
function query(){//returns $queryresult, $error and $query* for each sql statement.
global $queryresult, $error;
$queries=func_get_args();
foreach ($queries as $key => $value) {
$qnum=$key +1;
global ${"query{$qnum}"};
if (!${"query{$qnum}"} = mysql_query($value)){
$error++;
echo '<br><font color="red"><strong>There was a problem with sql'.$qnum.':</strong></font><br>
'.$value.'<br><font color="red"><strong>The error given was:</strong></font><br>'.mysql_error().'<br>';
}else{
$queryresult .="<br>Query$qnum ---$value--- OK<br>";}
}
if ($error==0){
return true;
}else { return false;}
}
That code is an absolute nightmare (no offense). Ignoring all the malpractice and global usage, what is the error what is given when the query fails? It would be helpful to see the queries that fail. Perhaps you should be logging (or displaying echo'ing if this is a test server) all the queries that do not work as expected.
gosh, is it that bad? in my defense i'm kinda new to the whole php thing, i just play around with it in my own time...
the idea is to be able to pass as many sql statements to the function and the function would return (make global) a variable called $query1 for the first $query2 for the second etc. which would hold the resultset for that query. when a query does go wrong the function should return false and echo the error information.... this is handled from line 13-21.... any ideas on how i would fix it up?
Problems with your code:
-Instead of using func_get_args(); you should pass and array to the function with your queries.
-Don't do this: global ${"query{$qnum}"};. Just, don't
-global = bad (99.99% of the time)
remember that all code i write is 100% untested and I am drunk so take it as you get it. Anyway, my code is super simpler than your code and will return either an array of all the result sets or a string with the error message in it.
i hope you get over the hangover alright!
the reason i did it the way i did is because that function used to be written completely different - very un-abstract (is there a word for that?) and i have implemented it in many of my scripts, and those scripts pass variables and expect to receive resultsets like $query1... so to change every implementation would be a real pain... any way to save it?