Marcus
Marcus

Reputation: 627

How can I avoid using $conn in every single query?

I'm just changed my code from mysql to mysqli and it seems to be best if:

How can i avoid of using $conn in every single queries or some mysqli's functions?

$conn = mysqli_connect("localhost", "test", "", "world"); 
$result = mysqli_query($conn, "select * from user where id = '1'");
$result = mysqli_query($conn, "select * from company where name = 'marcus'");
$result = mysqli_query($conn, "...");
mysqli_real_escape_string($conn, "my string");

How can i do this?

mysqli_query("select * from user where id = '1'");
mysqli_real_escape_string("my string");

Using of $conn->query("...") is not what i'm looking for because it doesn't have auto suggest from Dreamweaver.

Upvotes: 0

Views: 241

Answers (4)

Albzi
Albzi

Reputation: 15609

You can only avoid using $conn in every single connection if you change your code to become object oriented (but this means using $conn->query).

I suggest maybe moving away from Dreamweaver (I'm sure a large amount of people will agree) and use something different like Sublime Text or another text editor. You can't then rely on auto-suggest but then you're learning as you have to remember what everything is.

If auto-suggest is what you like using however, then stick with Dreamweaver and unfortunately put up with having to keep including $conn.

I will add that most other text editors do include auto-suggest for variables, objects and more. I have mentioned Sublime Text but there are other paid for and free text editors like Coda and Notepad++.

Upvotes: 5

GromNaN
GromNaN

Reputation: 592

This will be against best practices, but you can define a new function using global variables.

$conn = mysqli_connect("localhost", "test", "", "world");

function sql_query($sql) {
    global $conn;
    mysqli_query($conn, $sql);
}

sql_query("select * from user where id = '1'");

Upvotes: 1

Martin
Martin

Reputation: 22760

You can't. If your principle reason is auto suggest on Dreamweaver then I recommend either:

  • Using a OO shaped structure
  • Using another IDE
  • Learning your code so you don't need to rely on dreamweaver auto suggest
  • Ignore DW.

Upvotes: 2

Eric
Eric

Reputation: 18922

Put $conn = mysqli_connect("localhost", "test", "", "world"); in a separate file, like conn.php and include() that in the top of all your pages you need to access MySQL.

Upvotes: 0

Related Questions