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




  1. Go to the "Config" folder.
  2. Open "database.php".
  3. Enter the 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