Search code examples
phpmysqlsoappdobindparam

PHP PDO returning null column names


I am developing SOAP service in PHP.
Recently I have came across an issue when retrieving results from MySQL.
Problem
When retrieving results I get more columns than specified in my SQL statement. This is affecting my code when processing retrieved information. For example when I change fetch() to fetchAll(), I can't process more than one record. Is there any way to tell PHP or MySQL to return EXACTLY the columns that I need and not return this rubbish?
example code

$stmt2 = $pdo2->prepare("SELECT `id`, `username`, `IP_address` FROM PADR_users WHERE `username` LIKE :username");
$stmt2->bindParam(':username',$searchParam, PDO::PARAM_STR, 20);
$stmt2->execute();
$tmp = $stmt2->fetch(PDO::FETCH_ASSOC);
$response->return = var_export($tmp, true);

This will produce:

object(stdClass)#4 (1) { ["return"]=> string(193) "array ( 'id' => '19', 'username' => 'Batman2', 'IP_address' => '192.168.0.1' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '', )" }

Before I call MySQL I also tried using these:

$pdo2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo2->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);

However it doesn't make even a slightest difference.
Note
I have left intentionally the fetch() and not fetchAll() to eliminate possibility that the implementation of fetchAll() could have influenced the results.


Solution

  • You are only retrieving only 3 columns. However, the IP address has some null data at the end of it. You can tell by the concatenation operator between the strings:

    'IP_address' => '192.168.0.1' . "\0" . '' . "\0" . '' . "\0" . '' 
                                  ^      ^    ^      ^    ^      ^