Moving from mysql to mysqli

I want to change from mysql to mysqli here is how I organized my code:

connection.php
[php]

$host = mysql_connect(‘localhost’, ‘user’, ‘password’);
$db = mysql_select_db(‘db’);

[/php]

functions.php

[php]
function name(){

}

[/php]

header.php

[php]

require(‘connection.php’);
require_once(‘functions.php’);

[/php]

This is how I do it but to do it with mysqli its a bit complicated for me.Even though I have tried mysqli and used it I found it hard to organise.

How did you do it ? and what do you suggest for me ?

p.s:I know some of you will say PDO but thats complicated for me right now

It would be helpful with some examples with what you find complicated/confusing.

well when I try to parse mysqli_query($host,SQL);

$host is missing because its in connection file and I did not include it in functions…

well maybe I make the connection in functions and than connection would be in same place as functions and I would delete connection.php
right ?

The main thing to remember is, any connections, variable, or values you want to use later on, need to be included or required before you try to use them. The organization of mysqli should be the same as mysql_.

Part of it will depend on your approach, doing things in an OOP style will be utilized differently than in a procedural style.

well if you dont have the connection variable in same file as functions you cannot send query.

If you include/require file A before file B then variables you initialize in file A will be available in file B.

You are probably hitting scope issues

[php]$conn = new Mysqli…etc

function doSomething() {
// $conn is not available here
}

// $conn is available here[/php]

What you should do is pass the variables you need into the functions

[php]$conn = new Mysqli…etc

function doSomething($conn) {
// $conn is now available here
}

// wherever you call the function
$result = doSomething($conn);[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service