Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysqli version of mysql pattern

Tags:

php

mysql

mysqli

Here's a MySQL pattern in PHP:

$username="username";
$password="password";
$database="username-databaseName";

// Opens a connection to a mySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die("Not connected : " . mysql_error());
}

// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ("Can\'t use db : " . mysql_error());
}

// Search the rows in the markers table
$query =  some query
$result = mysql_query($query);

I tried to replace most of it with a mysqli pattern and then stick the query part at the bottom like so:

//Database Information
$db_host = "localhost"; //Host address (most likely localhost)
$db_name = "username-databaseName"; //Name of Database
$db_user = "username"; //Name of database user
$db_pass = "password"; //Password for database user

/* Create a new mysqli object with database connection parameters */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
GLOBAL $mysqli;

if ($mysqli->connect_errno) {
        echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
        exit();
    }

// Search the rows in the markers table
$query =  some query
$result = mysql_query($query);

However, I get this error message:

Invalid query: No database selected

What am I doing wrong?

like image 372
thanks_in_advance Avatar asked Nov 01 '22 15:11

thanks_in_advance


1 Answers

First of all, you're calling mysql_query and not mysqli_query, like you intended to.

Second, since you're using the object oriented form, you need to call mysqli_query as a method:

$result = $mysqli->query($query);
like image 196
Mureinik Avatar answered Nov 15 '22 05:11

Mureinik