Joe Lowery
Joe Lowery

Reputation: 572

Cloud SQL using mysqli error

I'm trying to output the results of a simple query using a Google Cloud SQL with a mysqli connection. I've properly set up a Cloud SQL instance and imported a SQL database. However, when I run my app, it seems to connect to the database - no errors are triggered there - but the logs show the following:

PHP Fatal error:  Wrong SQL: SELECT * FROM students Error: No database selected in /base/data/home/apps/s~db-php-001/1.371796924944999585/main.php on line 18

Here's my code:

$conn = new mysqli(null,"root","",null,null,"/cloudsql/db-php-001:db-instance-001");

// check connection
if($conn->connect_error) {
    trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
}

$sql='SELECT * FROM students';

$rs=$conn->query($sql);
if($rs === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
  $rows_returned = $rs->num_rows;
}

Obviously, I'm triggering that error, but I'm can't figure out why. There is definitely a table named students in the database.

Anyone have any ideas?

Thanks!! Joe

Upvotes: 1

Views: 2158

Answers (2)

Tony Tseng
Tony Tseng

Reputation: 479

To clarify, you can pass null for the database name. In the query you'd need to use the fully qualified table name (<database>.Students in your case). Or you can use the mysqli_select_db() function to select the database to use.

Upvotes: 0

user399666
user399666

Reputation: 19879

You've set your database name to null. A connection is made like so:

$mysqli = new mysqli("localhost", "user", "password", "database");

The mysqli constructor can take in the following parameters (in this order):

$mysqli = mysqli($hostname, $username, $password, $database, $port, $socket);

In your case, you've set the parameters to be:

$hostname = null; //Defaults to mysqli.default_host
$username = "root";
$password = "";
$database = null; //Defaults to "" 
$port = null; //Defaults to mysqli.default_port
$socket = "/cloudsql/db-php-001:db-instance-001";

Upvotes: 3

Related Questions