How do you bind / retrieve data from MYSQL database using objects in PHP?

Typically, I connect and retrieve data in the standard way (the error is removed for simplicity):

$db = mysql_select_db("dbname", mysql_connect("host","username","passord"));
$items = mysql_query("SELECT * FROM $db");

while($item = mysql_fetch_array($items)) {
    my_function($item[rowname]);
}

      

Where my_function does some useful stuff with this particular line.

What is the equivalent code using objects?

+1


source to share


2 answers


Since version 5.1 PHP comes with a PDO driver that provides a class for prepared statements.

$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password); //connect to the database
//each :keyword represents a parameter or value to be bound later
$query= $dbh->prepare('SELECT * FROM users WHERE id = :id AND password = :pass');

# Variables are set here.
$query->bindParam(':id', $id); // this is a pass by reference 
$query->bindValue(':pass', $pass); // this is a pass by value

$query->execute(); // query is run

// to get all the data at once
$res = $query->fetchall();
print_r($res);

      

see the PDO driver at php.net

Note that this way (with prepared statements) will automatically delete whatever it should be, and is one of the safest ways to do mysql queries if you use binbParam or bindValue.



There is also a mysqli extension to do a similar task, but I personally find PDO to be cleaner.

What's going in this direction and using all these steps, you are arguably a better solution than anything else when it comes to PHP.

Then you can use $ query-> fetchobject to retrieve your data as an object.

+3


source


You can use mysql_fetch_object ()



http://is2.php.net/manual/en/function.mysql-fetch-object.php

+2


source







All Articles