-1

enter image description here

I am trying to echo or print the last value of column usercode using PHP PDO. I tried to do this by using name column and SESSION var which will be the last values as references, but it doesn't work.

$name = $_SESSION['name'];

$query = $db->prepare("SELECT usercode from users where name = $name ");
$query->execute();

$result = $query->setFetchMode(PDO::FETCH_ASSOC); 

echo $result;
4
  • setFetchMode sets a mode. It does not fetch any result. Commented Feb 4, 2017 at 10:49
  • 1
    There are examples in the PDO manual. Try doing proper research before posting question. Commented Feb 4, 2017 at 10:52
  • I even give you a link php.net/manual/en/… Commented Feb 4, 2017 at 10:52
  • You should be getting an error from that query, since you didn't put quotes around $name. But you should use bound parameters, then that's not a problem. Commented Feb 4, 2017 at 11:10

1 Answer 1

0

Here you go:

$name = $_SESSION['name'];

$query = $db->prepare("SELECT usercode from users where name=:name");
$query = $db->bindParam(':name', $name);
$query->execute();

$row = $query->fetch();

echo $row['usercode'];

bindParam is used when you just want to bind a variable reference to a parameter in the query.

Sign up to request clarification or add additional context in comments.

5 Comments

Dont need to use named paramaters. You can also use question marks which is similar to mysqli
@SuperDJ I don't really see a difference between the two... really it depends if you're using PDO with MySQLi or PDO with prepared statements... I've always gone with the second one.
@SuperDJ You don't have to, but why wouldn't you? It makes queries and bindParam() calls so much easier to read.
just thoughts: I think it is a bit long when there is only one parameter. also, I am not a fan of bound parameters. I would: $db->prepare("SELECT usercode from users where name = ?); and: $query->execute([$name]); in this case.
@TheCodesee, JFYI: fetchColumn()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.