This article mainly introduces the PHP implementation of using PDO to read data from the database table method, interested in a friend's reference, I hope to be helpful to everyone.
Once the PDO object has been created, it is possible to retrieve the data by creating the object. Query data We can use the Pdo::query () method, the specific code is as follows:
try{ $pdo =new PDO (' Mysql:host=localhost;dbname=alpha ', ' root ', ' password ');} The catch (Pdoexception $e) { echo "database connection failed because:". $e->getmessage ();} Select the data from the database and assign the result to a variable, testtable the database table $result= $pdo->query (' Select Id,name,age from TestTable '),//The data output that will be queried while ($row = $result->fetch ()) { echo "ID:". $row [' id ']; echo "Name:". $row [' name ']; echo "Age:". $row [' Age '];}? >
As you can see from the code above, we use a while loop to output the query results.
Description:the Fetch () method calls the method each time it receives a row of data from the result set (in the form of an array), and then executes a while loop when a row of data is removed (as the pointer is automatically moved to the next row of data here), and if the next row of data exists, it is removed. Returns False if not present, ending the loop.
Another way to extract the data is: Fetchall (), from the name we can determine its meaning, is to retrieve all the data rows at once.
Note:both the Fetch () and Fetchall () methods accept the Fetch_style parameter, which defines how the result set is formatted.
PDO provides easy-to-use constants:
PDO::FETCH_ASSOC completed the above code as seen in the while loop, using the key group to return the array to the column name.
such as: Print_r ($result->fetch (PDO::FETCH_ASSOC));
Output: Array ([username] = Alpha [level] + 1 [signtime] =)
Pdo::fetch_num also returns an array, returning the numeric key used.
Pdo::fetch_both is the default value, combined with both of the above, returns the key group and the number key, which is the default way we use most