Welcome Guest, Not a member yet? Register   Sign In
Connect to DB in external Library (CI 4)
#1

(This post was last modified: 12-01-2020, 06:56 AM by henry_miaomiao.)

I have my custom library in Codeigniter 4:

<?php namespace App\Libraries;

class MyUrlang {

function __construct() {

//$conn = \Config\Database::connect();
}

public function get_url_lang($page = '', $var = ''){

$conn = db_connect();

$sql = "SELECT * FROM tab1 LIMIT 1";

$result = mysqli_query($conn, $sql);

$row = mysqli_fetch_assoc($result);

etc etc
}
}

In can't connect using mysqli_query... i receive this error: mysqli_query() expects parameter 1 to be mysqli, object given

I user connection in every my controller and model with no problem.

Which is the better way?

(12-01-2020, 06:43 AM)henry_miaomiao Wrote: I have my custom library in Codeigniter 4:

<?php namespace App\Libraries;

class MyUrlang {

function __construct() {
   
        //$conn = \Config\Database::connect();
    }

public function get_url_lang($page = '', $var = ''){

    $conn = db_connect();
                       
    $sql = "SELECT * FROM tab1 LIMIT 1";

    $result = mysqli_query($conn, $sql);
     
    $row = mysqli_fetch_assoc($result);

    etc etc
}
}

In can't connect using mysqli_query... i receive this error: mysqli_query() expects parameter 1 to be mysqli, object given

I user connection in every my controller and model with no problem.

Which is the better way?


print_r($conn) I receive the array with every parameters of the connection (password, host etc)... but mysqli_query does not work..
Reply
#2

You don't need to use mysqli_query directly. The documentation explains how to connect to databases and execute queries: https://codeigniter.com/user_guide/database/index.html
Reply
#3

(This post was last modified: 12-01-2020, 09:27 AM by henry_miaomiao.)

(12-01-2020, 07:01 AM)craig Wrote: You don't need to use mysqli_query directly. The documentation explains how to connect to databases and execute queries: https://codeigniter.com/user_guide/database/index.html

I have choose CI from the second version for the opportunity of use your code inside the famework.

Please, give me an example for make a query inside my own library
Reply
#4

Quote:Please, give me an example for make a query inside a own library

This is explained in the documentation that I linked to in my previous post - https://codeigniter.com/user_guide/datab...ar-queries

Code:
$query = $db->query('YOUR QUERY HERE');
Reply
#5

(12-01-2020, 09:22 AM)craig Wrote:
Quote:Please, give me an example for make a query inside a own library

This is explained in the documentation that I linked to in my previous post - https://codeigniter.com/user_guide/datab...ar-queries

Code:
$query = $db->query('YOUR QUERY HERE');

Thanks; the documentations (tutorial, examples etc) it's very little for CI4... compared with CI2 and CI3
Reply




Theme © iAndrew 2016 - Forum software by © MyBB