Skip to main content

How to use PHP PDO Fetch Class

php pdo fetch class


In this tutorial, you will learn how to use and create the PHP PDO fetch class mode (PDO::FETCH_CLASS ) to fetch data from the database.

Before entering in this tutorial, you will need to learn and read the php fetch pdo and examples.

Here, I just created a database and named it a PHP tutorial and create a table, and named a student.




Create table student
(
id int not null AUTO_INCREMENT,
student_name varchar(50) not null,
dept_name varchar(50) not null
);
  


so, the student's class name is php. php fetch class returns a new instance of the requested class, each row in the student table mapping the columns of the result set to named properties in the student class.

 

 $ads={1}

 

Read also:

How to add html responsive table in blogger and wordpress

How to create a accordion ui design Examples in html

8 Best Free Keyword Research Tools for SEO

What is domain and web hosting

Now connect the php pdo connection database using the dbconfig.php script:



<?php
$db_host="localhost";
$db_user="root";	
$db_password="";	
$db_name="phptutorial";	

try
{
	$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
	$e->getMessage();
}

?>




<?php

class student
{
}

 require 'dbconfig.php';

$sql = 'SELECT student_name,dept_name
        FROM student'
 ;

$stmt = $db->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_CLASS, 'student');
$student = $stmt->fetch();

var_dump($student);

?>


Output:



object(student)#3 (2) 
{ 
["student_name"]=> string(12) "chandrakumar"
["dept_name"]=> string(3) "cse" 
}


In the above code, using fetch() and it's select a first row from the student table.


$stmt->setFetchMode(PDO::FETCH_CLASS, 'student');


Above the code format that is set to the fetch mode and passes the student class name to the second argument of the setFetchMode() method and follows the code and executes the statement to get the result set.

Assigning class properties:


if there are some rules to be followed, which method you will be assigning the columns values to the object will be returned by the query to the corresponding class properties.

it the student class has a property, which name is the same as a column name and it's assigned the column value to the property.

if the class property has no property the php will call the magic method to __set() the value to call and execute.

If there is no __set() method and the php will create a public property to call the value.



<?php
require 'dbconfig.php';
class studentclass
{
    private $student_name;
	private $dept_name;

   public function __set($name,$dept)
  {
    echo $this->student_name .'<br/>';
	echo $this->dept_name;
    }
}
$sql= "SELECT student_name,dept_name FROM student where id = :id";
$stmt = $db->prepare($sql);
$stmt->execute([':id' => 1001]);
$stmt->setFetchMode(PDO::FETCH_CLASS, 'studentclass');
$student = $stmt->fetch();
var_dump($student);
?>

Output:


object(studentclass)#3 (2) { 
["student_name":"studentclass":private]=> string(12) "chandrakumar" 
["dept_name":"studentclass":private]=> string(3) "cse" 
}


<?php
class student
{
    private $student_name;
	private $dept_name;

    public function getdetails()
    {
        echo $this->student_name .'<br/>';
		echo $this->dept_name;
    }
}

$stmt = $db->query("SELECT * FROM student");
$stmt->setFetchMode(PDO::FETCH_CLASS, 'student');
$student = $stmt->fetch();
$student->getdetails();
?>

Output:



chandrakumar
cse

Assigning Object:



<?php
require 'dbconfig.php';
class student
{
    private $student_name;
   private $dept_name;

   public function getdetails()
  {
    echo $this->student_name .'<br/>';
	echo $this->dept_name;
    }
}
$sql= "SELECT student_name,dept_name FROM student where id = :id";
$stmt = $db->prepare($sql);
$stmt->execute([':id' => 1001]);
$stmt->setFetchMode(PDO::FETCH_CLASS, 'student');
$student = $stmt->fetch();
$student->getdetails();
?>

Output:



chandrakumar
cse


In the above example code , student class has two private properties and an __set() method.

here, the private properties are student_name,dept_name with the columns name from the selected row,and it's php assings the columns values to these properties.

Assigning object properties and calling constructor:


In the below code, PDO assigns column values to the object properties before calling the constructor and get the result on getdetails() and fetch the data from the id and mention the id value as ':id' => 1001.



<?php
require 'dbconfig.php';

class student
{
    private $student_name;
	private $dept_name;

   public function __construct()
  {
    $this->getdetails();
    }
  public function getdetails()
  {
	echo $this->student_name .'<br/>';
	echo $this->dept_name;
  }
}
$sql= "SELECT student_name,dept_name FROM student where id = :id";
$stmt = $db->prepare($sql);
$stmt->execute([':id' => 1001]);
$stmt->setFetchMode(PDO::FETCH_CLASS, 'student');
$student = $stmt->fetch();
$student->getdetails();
?>

Output:


chandrakumar
cse chandrakumar
cse

Comments

Popular posts from this blog

Contact Management System project using C with source code

Contact Management System (CMS)   A Contact Management System (CMS) is an essential application for organizing and managing contacts efficiently. Here's a simple implementation of a Contact Management System using C, allows users to perform operations such as adding, viewing, searching, modifying, and deleting contacts through a simple and user-friendly console interface. The CMS provides a practical demonstration of fundamental programming concepts such as arrays, structures, and string manipulation, making it an excellent project for students and beginners in C programming.   Project Overview The Contact Management System is designed to store basic information about contacts, including: Name: name of the person. Phone Number: phone number of the contact. Email Address: email address of the contact.   With this information, the program offers the following functionalities: Add New Contact...

Implementing Basic Add to Cart Functionality in Python Using Flask

In e-commerce websites, the "Add to Cart" feature allows users to select products they want to purchase and store them temporarily while they continue shopping. Implementing this functionality in a web application using Python and Flask is straightforward and can be done with a few simple steps.       Setting Up the Project: First, create a new directory for your project and set up a virtual environment to manage dependencies. Install Flask using pip and create three main files: `app.py`, `index.html`, and `cart.html`.   Read also:   Unlocking the Power of Free Google Tools for Seo Success Ultimate Guide: Google Search Console Crawl Reports you need to know Monitor What is dofollow backlinks: The ultimate 5 Benefit for your websites SEO Schema markup and How can you use schema markup for seo      Creating HTML Templates: Create HTML templates for displaying products (`index.html`) and the shopping cart (`cart.html`). These templates will use ...

Advanced HTML Concepts: Techniques and Examples for Modern Web Development

Advanced HTML goes beyond the basics of creating simple web pages, delving into powerful features and techniques that improve web interactivity, accessibility, and performance. It includes concepts such as semantic HTML, custom data attributes, responsive images with <picture> , enhanced forms, interactive content using <details> and <summary> , and embedding external resources with <iframe> .          Furthermore, advanced HTML focuses on SEO optimization through meta tags, accessibility improvements using ARIA, creating reusable Web Components, and optimizing performance with async and defer scripts.    Semantic HTML   Semantic elements clearly describe their meaning in a human- and machine-readable way.   <header> <h1>Welcome to My Website</h1> </header> <nav> <ul> <li><a href="home">Home...

Python Flask Student List CRUD System Using MySQL Database for Beginners

  In this tutorial, we are going to learn the python flask student list crud system using MySQL database for beginners. Before you have to learn how to python flask setting up and connect MySQL database connection and templates uses.    Read also: Python Flask tutorial Setting up a Flask and Sql Database on the create project folder you have to install two things to fetch data and flask. Here, below code to install using python terminal, and for MySQL, am using xampp software and database inside environment to turn on the apache server and MySQL database.   Read also: Python Flask with Mysql Database Import Flask and MySQL: from flask import Flask, render_template, request, redirect, url_for from flask_mysqldb import MySQL MySQL Database Connection: app = Flask(__name__) app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '' app.config['MYSQL_DB'] ...

Microdata Schema : How can Microdata schema Improve SEO with Examples

In this article, we will explore what microdata schema is, how it works, and provide some examples to help you better understand its importance. What is Microdata Schema? Microdata schema is a markup language that provides a standardized way of adding structured data to web pages. It uses HTML tags to describe information about the content on a web page, such as product reviews, events, recipes, and more. This makes it easier for search engines to crawl and index the content on a web page, which can help improve the visibility and ranking of the website. How Does Microdata Schema Work? Microdata schema uses a set of properties and item types to describe the content on a web page. Properties describe specific attributes of an item, while item types describe the type of item being described. For example, the property "name" might be used to describe the name of a person, while the item type "Person" would be used to indicate that the content being describ...

How to Create a Personal details information program in HTML

In this tutorial, we are learning how you can create a personal details information program in HTML with the simple using of HTML tags. HTML Form: <div class="container"> <h1 style="text-align:center">Personal Details</h1> <form class="form-control"> <label for="name">Name:</label><br> <input type="text" id="name" name="name"><br> <label for="email">Email:</label><br> <input type="email" id="email" name="email"><br> <label for="dob">Date of Birth:</label><br> <input type="date" id="dob" name="dob"><br> <label for="gender">Gender:</label><br> <input type="radio" id="gender" name="gender" value="male...