0

I have this problem I can't figure out, I query the DB this way:

$stmt = $this->pdo->prepare('SELECT customer_name FROM active_users WHERE a_id= ?');
$stmt->execute(array($a_id));
$c_name = $stmt->fetch(PDO::FETCH_OBJ);
API::writeToLog('CMD=leave , Customer_Name = ' . $c_name->customer_name, $customer_name);

This: $c_name->customer_name gives the following error :

Notice: Trying to get property of non-object

How can I iterate my database, and whats the difference between fetch and fetchAll ? which should I use?

This is the DB schema:

+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| a_id          | varchar(40)  | NO   | PRI | NULL    |       |
| token         | varchar(64)  | NO   |     | NULL    |       |
| nick          | varchar(255) | NO   |     | NULL    |       |
| ip            | varchar(32)  | NO   |     | NULL    |       |
| customer_name | varchar(255) | YES  |     | NULL    |       |
+---------------+--------------+------+-----+---------+-------+

thanx!

EDIT: fixed a typo..

2 Answers 2

3

You should add an if condition to check whether the record exists.

$stmt = $this->pdo->prepare('SELECT customer_name FROM active_users WHERE udid = ?');
$stmt->execute(array($udid));
if ($c_name = $stmt->fetch(PDO::FETCH_OBJ)) {
  API::writeToLog('CMD=leave , Customer_Name = ' . $c_name->customer_name, $customer_name);
}

For fetchAll, it returns all the records at once.

As @Darragh pointed out, you have a typo for $c_name.

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

3 Comments

+1 always good practice to check your returned assignment values
when using the fetchAll like this: $messages = $stmt->fetchAll(PDO::FETCH_OBJ); should I use 'if' to check the returned value as well? if so, iterating over the pdo objects will be as followed ? : foreach ($messages as $message) { ... }
@Li3ro You just need iterate it.
0

Typo? Should it not be $cname->customer_name instead of $c_name->customer_name?

EDIT

To be specific, you're assiging your return object to $cname:

$cname = $stmt->fetch(PDO::FETCH_OBJ);

But you're referring to $c_name on the next line:

API::writeToLog('CMD=leave , Customer_Name = ' . $c_name->customer_name, $customer_name);

1 Comment

You right, its a typo when editing the question, not in code.. sry

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.