0

Can someone please tell me why my function is not working?

function myappsbdo($sqlquery, $tabname)
{
try
 {
 $pdo = new PDO("mysql:host=127.0.0.1;port=3306;dbname=myapps","root","");
 }
catch (PDOException $e)
 {
 echo "Problème de connexion";
 exit();
 }
$sql = $sqlquery;
 $result = $pdo->query($sql);
 $tabname = $result->fetchALL(PDO::FETCH_NUM);
}

I do a var_dump of the variable I chose for my $tabname and it's an empty array. There is suppose to have my db data in it... Thanks!

EDIT: this is how I call it. myappsbdo("SELECT * FROM categorie", $tab1);

asked Dec 14, 2012 at 1:45
1
  • What is the value of $tab1 when you call it? Seems like it is not initialized yet. Commented Dec 14, 2012 at 1:57

1 Answer 1

1

The function argument $tabname was passed by value, therefore your subsequent assignment to that variable changes only the value of the function-scoped variable $tabname and not of the calling-scoped variable $tab1.

You want to pass by reference instead:

function myappsbdo($sqlquery, &$tabname) {
 // ^---- notice the ampersand character
 // etc.
 $tabname = $result->fetchALL(PDO::FETCH_NUM);
}

Or, alternatively, return the resultset:

function myappsbdo($sqlquery) {
 // etc.
 return $result->fetchALL(PDO::FETCH_NUM);
}
$tab1 = myappsbdp('SELECT * FROM categorie');

Note that you probably ought to make your PDO object static, so that the database connection can be reused in successive function calls.

answered Dec 14, 2012 at 2:12
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I forgot to return the value haha.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.