2

I try to create a new folder for each new registration but I do have troubles with naming them after their unique registration id.

In my database each new user gets a userid. To select the latest userid I use the SQL Statement

$sql = "SELECT max(userid) FROM User";

So far so good, PHPMYADMIN shows me the correct result, but I don't know how to save this single result in a variable in PHP. Read through the PHP manual and tried the different fetch options but either I didn't get it or the result was different from what I wanted.

Right now I can only print all the results, but not the one I want with this:

foreach ($db->query($sql) as $row) {
  echo $row['userid'] . "<br />";
}

The goal is to get this thing to work:

mkdir("uploads/$userid", 0755, true);

Any help would be appreciated. I'm getting really frustrated with this!

EDIT: Okay went for the easy route and named the directory after a hash from the email. Still it would interest me: If I use $sql = "SELECT max(userid) FROM User"; How do I bind the result to a variable in PHP?

D. M
  • 31
  • 3
  • Are you running the SAME query? – Damien Pirsy Dec 18 '15 at 15:45
  • `SELECT max(userid) as uid FROM User` you can also add an `as` to your statement to guarantee name of result – E_p Dec 18 '15 at 15:51
  • The SELECT statement selects the correct value but I can't use it somehow. Is there a way to store the output of my query in a variable? Tried the different pdo fetch things but didn't really work – D. M Dec 18 '15 at 16:18

2 Answers2

4

If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.

When a new AUTO_INCREMENT value has been generated, you can also obtain it by executing a SELECT LAST_INSERT_ID() statement with mysql_query() and retrieving the value from the result set returned by the statement.

You can also reference this post:

How do I get the last inserted ID of a MySQL table in PHP?

Community
  • 1
  • 1
Yaco Zaragoza
  • 429
  • 1
  • 7
  • 18
  • This extension was deprecated in PHP 5.5.0 instead use PDO::lastInsertId() – Keyne Viana Dec 18 '15 at 15:54
  • Thanks for the answer, tried to use this before but all I got was 0 as a result. Right now I have put the "echo $db->lastInsertId();" under my query but it is also only showing a 0. Here is a pastebin of the code, maybe you see the error? http://pastebin.com/8TBCPzn9 – D. M Dec 18 '15 at 16:14
1

So instead of echoing the result out, why not use it to make that dir?

foreach ($db->query($sql) as $row) {
 mkdir("uploads/$row['userid']");
}
Siim Kallari
  • 851
  • 6
  • 17