mysql_fetch_object

(PHP 4, PHP 5)

mysql_fetch_object結果の行をオブジェクトとして取得する

警告

この拡張モジュールは PHP 5.5.0 で非推奨になり、PHP 7.0.0 で削除されました。 MySQLi あるいは PDO_MySQL を使うべきです。詳細な情報は MySQL: API の選択 を参照ください。 この関数の代替として、これらが使えます。

説明

mysql_fetch_object(resource $result, string $class_name = ?, array $params = ?): object

取得された行を表すプロパティを有するオブジェクトを返し、 内部のデータポインタを前に進めます。

パラメータ

result

評価された結果 リソース。この結果は、mysql_query() のコールにより得られたものです。

class_name

インスタンス化し、プロパティを設定して返すクラスの名前。 指定しなかった場合は stdClass オブジェクトが返されます。

params

class_name オブジェクトのコンストラクタに渡す オプションのパラメータの配列。

戻り値

取得された行を表す文字列プロパティを有するオブジェクト(object)を返します。 もう行が残っていない場合は、false を返します。

例1 mysql_fetch_object() の例

<?php
mysql_connect
("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
while (
$row = mysql_fetch_object($result)) {
echo
$row->user_id;
echo
$row->fullname;
}
mysql_free_result($result);
?>

例2 mysql_fetch_object() の例

<?php
class foo {
public
$name;
}

mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");

$result = mysql_query("select name from mytable limit 1");
$obj = mysql_fetch_object($result, 'foo');
var_dump($obj);

注意

注意: パフォーマンス

速度面では、この関数は mysql_fetch_array() と同等で、 mysql_fetch_row() とほぼ同等です(違いはわずかです)。

注意:

mysql_fetch_object()は、配列の代わりに オブジェクトが返されるという一つの違いを除いて mysql_fetch_array()と類似しています。 つまり、オフセットによってではなく、フィールド名によってのみ データにアクセスすることができます (数字は、プロパティ名として使用できません)。

注意: この関数により返されるフィー ルド名は 大文字小文字を区別 します。

注意: この関数は、 NULL フィールドに PHPの null 値を設定します。

参考

add a note add a note

User Contributed Notes 24 notes

up
7
mp
16 years ago
When working with a stdClass object returned from a database query, specifically:

$object = mysql_fetch_object($result)

You may run into assignment problems if you have a field with a '.' in the name.
e.g.: `user.id`

To remedy this situation, you can use curly braces and single quotes during assignment.

In place of:
$myObject->user_id = $object->user.id;

Use:
$myObject->user_id = $object->{'user.id'};
up
4
Peter T
16 years ago
If you're using mysql_fetch_object and specifying a class - the properties will be set BEFORE the constructor is executed.  This is generally not an issue, but can cause some major problems if you're properties are set via the __set() magic method and constructor logic must be executed first.
up
1
info [at] woeiweb [dot] nl
17 years ago
Since PHP 5.2.1 it seems like this function doesn't like queries that return columns with empty names, like:
select '' from `table`

PHP exits and mysql_error() does not return an error.
up
0
webmaster at kibab dot com
14 years ago
That huge difference in timings may be caused by database cache issues. If mysql_fetch_object() was the first function to be used, the cache was empty, but subsequent invocations took the result from the query cache.
up
0
Chris at r3i dot it
17 years ago
In reply to rodolphe dot bodeau at free dot fr :

The function mysql_fetch_object has other two parameters that you can use.
As the manual say:
mysql_fetch_object( $resource, $class_name, $params ) )

$class_name and $params are optional.

So if you want to fetch a row in a class you can:

1) Define your class Test with method and other stuff.
2) Execute Query
3) call:
$Object = mysql_fetch_object( $Resource, "Test" );

so you can use $Object with the methods

Be aware how you write code in your methods: in this case, classes are used for centralize the code and they are not
really safe because you can have an additional Information
( with a Join Query for example ) without methods to access to them.
So classes need get and set method generalized.
( for extra see PHP 5 Manual O'Rielly on the use of generalized methods get and set )
up
0
rodolphe dot bodeau at free dot fr
17 years ago
This little function stores the content of a mysql_fetch_object result into an object by using MySQL request field names as object parameters :

<?php
function FetchRequestInObject(&$obj, $req)
{
   
$ReqVars = get_object_vars($req);
    foreach (
$ReqVars as $ReqName => $ReqValue)
    {
        if (
property_exists($obj, $ReqName))
        {
           
$obj->$ReqName = $ReqValue;
        }
    }
}
?>

Remember that mysql_fetch_object is case sensitive, so beware of your object properties. Use keyword "AS" in your SQL request to change field name if necessary.
up
0
backglancer at hotmail
19 years ago
Watch out for mysql_fetch_object() to return all values as strings.
if you try to do
<?
$p
= mysql_fetch_object($some_sql);
// and then try to do something like

$money = $p->dollars + $p->cents;
?>

You may experience "Unsupported operand types"

so always cast them both as (int) 's!!
up
-1
hcse at op dot pl
16 years ago
<?php
class Test {
   
    public
$go ;
    private
$id ;
   
    function
show() {
        return
"id: {$this->id} go: {$this->go}" ;
    }
   
    function
__construct()
    {
        echo
"in __construct() ". $this->show() ."\n" ;
       
$this->go = uniqid()    ;
    }
   
}

if (! (
$res = mysql_query('SELECT * FROM `test`', $db))) {
    die(
'Invalid query: ' . mysql_error() . "\n");
}

while(
$obj = mysql_fetch_object($res, 'Test') ){
    echo
"outside ________ ". $obj->show() ."\n\n";
}
?>

This code gives the result:
in __construct() id: 1 go: first
outside ________ id: 1 go: 4845bd99ca2e3

in __construct() id: 2 go: second
outside ________ id: 2 go: 4845bd99ca2fd

It means that __construct() is invoked after filling fields with data from database, eg. it can be used to change strings into integers.
up
-1
trithaithus at tibiahumor dot net
19 years ago
This method offers a nice way to fetch objects from databases. As Federico at Pomi dot net mentioned it doesn't work native as the type of the object fetched isn't the right one, but with a small typecast it works flawlessly.

<?php
function ClassTypeCast(&$obj,$class_type){
   if(
class_exists($class_type)){
      
$obj = unserialize(preg_replace("/^O:[0-9]+:\\"[^\"]+\\":/i",
         "
O:".strlen($class_type).":\\"".$class_type."\\":", serialize($obj)));
   }
}

class Foo
{
    var
$foo;
    var
$bar;
    function get_from_db()
    {
        mysql_connect();
        mysql_select_db();
       
$res = mysql_query("SELECT foo,bar from my_table");
       
       
$fetched_object = mysql_fetch_object($res);
        ClassTypeCast(
$fetched_object,"Foo");
       
$this = $fetched_object;
    }
}
?>
up
-2
Justin Rovang
16 years ago
This is another way to load variables quickly within $this, and allows for intervention on variable names.

All columns from the single-row result are loaded and accessed via $this->_variableName.

<?
class MyClass{
    public function
_load($nID) {
       
$Q = "SELECT * FROM myTable";
        if(
$aTmp = RETURN_Q_ARRAY($Q)) {
           
$aTmp = $aTmp[0];
           
$aK =array_keys($aTmp);
            foreach(
$aK as $sK) {
                if(!
is_numeric($sK)) $this->{"_$sK"}=$aTmp[$sK];
            }
            return
true;
        }
        return
false;
    }
}

$o = new MyClass;
$o->_load(1);

echo
$o->_id; //1
echo $o->_otherColumn; //otherColumn value
up
-2
danielpunt
16 years ago
@Jezze : This wil also work. Also works with static methods.

<?php

class Foo
{
    private
$FooBar;

    public function
LoadFromId($Id)
    {
       
$Result = mysql_query('SELECT * FROM foo WHERE Id = ' . $Id);
        while(
$Row = mysql_fetch_object($Result, __CLASS__))
        {
           
print_r($Row);
        }
       
    }

}

$Foo = new Foo;
$Foo->LoadAll();

?>
up
-2
syntax
18 years ago
@Simon Paridon and others concerning SQL to php getting results via mysql_fetch_object:

Every query that would fail in a database frontend, such as MySQLs "Query Browser" and only will work by using the `-marks will probably give results hardly accessible in PHP especially if you have column names with "-" or " " in it.

Using the example of Simon Paridon: it is not possible to execute a query like:

SELECT id, user-id FROM unlucky_naming

only

SELECT id, `user-id` FROM unlucky_naming

will work...

so either be a bit wiser when naming the colums (e.g. user_id)

or try it with

SELECT id, `user-id` AS user_id FROM unlucky_naming

(i have not tested it in PHP yet, but i guess this will fail as well, if you have a query like "SELECT `foo name` FROM `unlucky naming 2`")

Somewhat down "amackenz at cs dot uml dot edu" mentioned to name sum, count etc. this may be a good hint for newbies: increase the speed of your php applications by using (my)sql native functions and save data transfer as well as processing time
up
-2
rcoles at hotmail dot com
21 years ago
In reviewing Eskil Kvalnes's comments (04-Mar-2003 11:59
When using table joins in a query you obviously need to name all the fields to make it work right with mysql_fetch_object()) I was left asking and, as a newbie, the reason why I'm here. I have a 28 field table. Ran SELECT * with a LEFT JOIN, etc and it appears to have worked on my test server without issue.

On further reading, MYSQL.COM has the following:
* It is not allowed to use a column alias in a WHERE clause, because the column value may not yet be determined when the WHERE clause is executed. See section A.5.4 Problems with alias.
* The FROM table_references clause indicates the tables from which to retrieve rows. If you name more than one table, you are performing a join. For information on join syntax, see section 6.4.1.1 JOIN Syntax. For each table specified, you may optionally specify an alias.

Aware of the fact there's a difference between tables and fields there appears to be confusion here somewhere.
up
-3
q
20 years ago
Some clarifications about previous notes concerning duplicate field names in a result set.

Consider the following relations:

TABLE_A(id, name)
TABLE_B(id, name, id_A)

Where TABLE_B.id_A references TABLE_A.id.

Now, if we join these tables like this: "SELECT * FROM TABLE_A, TABLE_B WHERE TABLE_A.id = TABLE_B.id_A", the result set looks like this: (id, name, id, name, id_A).

The behaviour of mysql_fetch_object on a result like this isn't documented here, but it seems obvious that some data will be lost because of the duplicate field names.

This can be avoided, as Eskil Kvalnes stated, by aliasing the field names. However, it is not necessary to alias all fields on a large table, as the following syntax is legal in MySQL: "SELECT *, TABLE_A.name AS name_a, TABLE_B.name AS name_b FROM TABLE_A, TABLE_B ...". This will produce a result set formatted like this: (id, name, id, name, id_A, name_a, name_b), and your data is saved. Hooray!

-q
up
-2
Federico at Pomi dot net
22 years ago
Be carefull:
the object returned will be a new/fresh object.

You can't use this function to replace some attributes of an existing object keeping the old ones.

Example:
class person
{
   var $name;
   var $surname;
   var $doh;

function print()
{
   print($name." ".$surname);
}

function get_from_db()
{
   $res=query("select name, surname from ppl where... limit 1");
   $this=mysql-fetch-object($res);
}

}

This won't work! When the method get_from_db() is executed, your old object will be destroyed... you won't find anything in the attribute $doh, and if you'll try to call the method print(), it will say it doesn't exist.
up
-3
strrev xc.noxeh@ellij
16 years ago
I created a table, with 5 INT columns, and 1000 rows of random ints.
I did 100 selects:

SELECT * FROM bench... (mysql_fetch_object)
Query time: 5.40725040436
Fetching time: 16.2730708122 (avg: 1.32130565643E-5)
Total time: 21.6803212166

SELECT * FROM bench... (mysql_fetch_array)
Query time: 5.37693023682
Fetching time: 10.3851644993 (avg: 7.48886537552E-6)
Total time: 15.7620947361

SELECT * FROM bench... (mysql_fetch_assoc)
Query time: 5.345921278
Fetching time: 10.6170959473 (avg: 7.64049530029E-6)
Total time: 15.9630172253

"Note: Performance  Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant)."

And I am a penguin :)
up
-3
Eskil Kvalnes
21 years ago
When using table joins in a query you obviously need to name all the fields to make it work right with mysql_fetch_object().
up
-3
spamme at aol dot com
21 years ago
This is probably a little more elegant:

$sql = "SELECT * FROM table ";
$result = mysql_query($sql);

$data = array();

while ($row = mysql_fetch_object($result))
   $data[] = $row;
up
-5
Kaminari (telecotxesco at hotmail)
18 years ago
This is a very very elegant (and costless) way to fetch an enterie query to every single field name from a "wide" table:

The tedious way fetching:
<?php
    $idtable
=mysql_connect("localhost","user","pwd");
   
mysql_select_db("table",$idtable);
   
$consult=mysql_query("SELECT *
                            FROM models
                            ORDER BY Serie,Year ASC"
);
    while(
$row=mysql_fetch_object($consult)){
       
$IdLomo=$row->IdLomo;
       
$Serie=$row->Serie;
       
$Model=$row->Model;
       
$Type=$row->Type;
       
$Year=$row->Year;
       
$Speed=$row->Speed;
       
$Power=$row->Power;
       
$Price=$row->Price;
       
$Load1=$row->Load1;
       
$Load2=$row->Load2;
       
$Load3=$row->Load3;
       
$Load4=$row->Load4;
       
$Server=$row->Servier;
       
$Real=$row->Real;
       
$Lomo=$row->Lomo;
    }
?>

Resulting on 15 new variables called like their name on table wich we introduced manualy for 5 minutes. But imagine each row has 100 fields!

A way saving time with the same result:

<?php
    $idtable
=mysql_connect("localhost","user","pwd");
   
mysql_select_db("table",$idtable);
   
$consult=mysql_query("SELECT *
                            FROM models
                            ORDER BY Serie,Year ASC"
);
   
// We find the fields number
   
$numfields=mysql_num_fields($consult);

   
// Now we put the names of fields in a Array
   
for($i=0;$i<$numfields;$i++){
       
$fieldname[$i]=mysql_field_name($consult, $i);
    }

    while(
$row=mysql_fetch_object($consult)){
       
//Finally we assign the new variables
       
for($i=0;$i<$numfields;$i++){
            $
$fieldname[$i]=$row->$fieldname[$i];
        }
    }
?>
up
-6
Jezze
17 years ago
If you have a class that represents itself in a database you can use this function to get the properties.

class MyClass {

  public $name;
  public $language;

  function load($id) {

    $query = mysql_query("SELECT name, language FROM myTable WHERE id = $id");
    $result = mysql_fetch_object($query, get_class($this));

    foreach(get_object_vars($result) as $var => $value) $this->$var = $value;
  }

}

$a = new MyClass();
$a->load(1);
up
-4
kalleanka
21 years ago
an addition to the previous...

for example getting members from a database:

function getAllMembers () {
    $query = "SELECT * FROM people ORDER BY lname";
    $result = mysql_query($query);
           
    while($member = mysql_fetch_object($result)){
        $members[] = $member;
    }
                   
    return $members;
}
<br><br>
    DON'T FORGET TO DECLARE THE ARRAY. If you try to cycle through members after the function has been called and you don't declare the array first you will get a horribly (HORRIBLY!) ugly error in your page. Also, if you try to add the object into the members array inside the while condition instead of in the while loop, you will generate one extra empty space in the array due to the last iteration/check.
up
-3
allen at brooker dot gb dot net
22 years ago
I found the above code to be buggy, not adding all the records to the array. This is the code I used instead:

  $command = "SELECT * FROM table ";
  $result = mysql_query($command, $link_id);
  $num = mysql_num_rows($result);

  $clickthru = array();

  for ($i = 0; $i <= $num; $i++) {
    $clickthru[$i] = array();
    $clickthru[$i] = mysql_fetch_array($result);
  }

Allen
up
-4
zhundiak at comcast dot net
21 years ago
Here is a wrapper that will allow specifying a class name.
function &db_fetch_object($set,$className)
{
  /* Start by getting the usual array */
  $row = mysql_fetch_assoc($set);
  if ($row === null) return null;

  /* Create the object */
  $obj =& new $className();

  /* Explode the array and set the objects's instance data */
  foreach($row as $key => $value)
  {
    $obj->{$key} = $value;
  }
  return $obj;
}
class CPerson
{
  function getFullName()
  {
    return $this->fname . ' ' . $this->lname;
  }
}
$set = mysql_query('SELECT fname,lname FROM person');
while($person =& db_fetch_object($set,'CPerson'))
{
  echo $person->getFullName();
}
up
-5
Simon Paridon
18 years ago
The behavior of this function is slightly questionable.

If you have a col in you table containing non-variable-name characters like "-", mysql_fetch_object will add "impossible variable names" to your object, e.g.

object (
  [user-id] => 7
)

You can not access this variable normally with $obj->user-id, because the variable name is invalid. But you can however access it like this:

$foo = 'user-id';
echo $obj->$foo;

It will correctly output 7, whereas var_dump($obj->user-id) would output int(0) for some reason.

I got this behaviour with PHP 4.4.2.
To Top