Articles → PHP CODEIGNITER → Connect to mysql database in php codeigniter

Connect to mysql database in php codeigniter






MySQL database




Picture showing the Class table in mysql

Click to Enlarge


Specify the database credentials










Picture showing the database configuration in config.php

Click to Enlarge


Database code in model




<?php
class mymodel extends CI_Model {
    public function GetUsers() {
        $this->load->database();
        $q = $this->db->query("select * from Class;");
        $result = $q->result();
        return $result;
    }
}




<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
	<head></head>
	<body>
		<div id="container">
			<div id="body">
				<ul>
					<?php foreach($users as $user ): ?>
					<li>
						<?= $user->ClassDisplayName ?>
					</li>
					<?php endforeach ?>
				</ul>
			</div>
		</body>
	</html>



Output




Picture showing the output of data retrieval from mysql

Click to Enlarge


How to return a single row?




$this->load->database(); // Commenting the code

$q = $this->db->query("select * from Class;");

if($q->num_rows() > 0)
{
	$result	= $q->row();
}




stdClass Object ( [ClassId] => 1 [ClassCode] => PLAYGROUP [ClassDisplayName] => Play group [AdmissionFees] => [MonthlyTutionFees] => [OtherFunds] => [Conveyance] => [ExaminationFees] => [LateFeeFine] => [RenewAdmissionFees] => [RenewExaminationFees] => )



Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, July 15, 2020
 
Updated On  -  Thursday, August 13, 2020

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250