1

I need some help. I have some nested SELECT statements that get the user's ID then use that ID to search another table in MySQL. I have a foreach() loop that uses the user_id from the first query to create a folder for the user if there isn't one in the filesystem. Then I used bindParam() to assign it a variable and use it in another query to get the user's name. However, it throws and exception saying 'Call to a member function bindParam() on null in C:\foo\bar\foobarscript.php on line 29'. Here's my code up until the break...

try {
$con = new PDO("mysql:host=$dbname;dbname=$db", $user, $pass);
//Set the PDO error mode to exception
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->beginTransaction();
$stmt = $con->prepare("SELECT user_id
                        FROM users");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$res = $stmt->fetchAll();
foreach($res as $row) {
    $uid = $row['user_id'];
    $filename = './reports/'.$uid.'';
    if(!file_exists($filename)) {
        if(!mkdir('./reports/'.$uid)) {
            die('Failed to create folders..');
        }
    }
    $stmt2->bindParam(':uid', $uid);     //<--- Code breaks here
    $stmt2 = $con->prepare("SELECT CONCAT(fname,' ',lname) as fullname FROM users WHERE user_id = :uid");
    $stmt2->execute();
    $fullName = $stmt2->fetchAll();
    $userArray[] = array_fill_keys($uid, $fullName);
    $stmt2->closeCursor();
}

I have searched up and down and tried rewriting it, debugging piece by piece. Everything works fine until I put it all back together and I get this error again. I really appreciate any help!

Edit: I have even tried removing the assigned variable and binding like:

$stmt2->bindParam(':uid', $row['user_id']);
Drew
  • 358
  • 3
  • 9
  • What is result of `var_dump($uid);`? – jagad89 Jul 12 '15 at 06:45
  • The user_id array prints. I know that portion works, because it is creating folders in the filesystem. Embarrassingly enough, I just reread through it and realized that my bindParam() functions were before my prepared statements causing it to think :uid was null. Thanks for looking at it though. – Drew Jul 12 '15 at 06:47
  • Just alter the lines like `$stmt2 = $con->prepare("SELECT CONCAT(fname,' ',lname) as fullname FROM users WHERE user_id = :uid");$stmt2->bindParam(':uid', $uid);` Error because of `$stmt2` was null. – jagad89 Jul 12 '15 at 06:48
  • Yup, that's what I did. Thank you! – Drew Jul 12 '15 at 06:49

0 Answers0