Cloud SQL using mysqli error - php

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

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";

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.

Related

MySQL error message, mysql_connect(), any way to fix it?

So this is the error message:
PHP Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
This is the affected piece of code:
class wdClient {
var $dbLink; // The database link
var $prefix; // Table prefix
var $script; // The script running
/**
* Construct a new directory object.
*/
function wdClient() {
error_reporting(E_ALL ^ E_NOTICE);
$this->prefix = WDDBPREFIX;
// Connect to the database
$this->dbLink = mysql_connect(WDDBHOST, WDDBUSER, WDDBPASSWD);
// Select the database
mysql_select_db(WDDBNAME, $this->dbLink) or die('Sorry, The site is currently unavailable!');
}
where WDDBPREFIX, WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME are already defined in a config file.
I have tried simply using mysqli_connect instead of mysql_connect but it's not working.
Note: Never use MySQL, use this method!
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
Good luck!
well, as pointed in here http://php.net/manual/en/function.mysqli-connect.php , you should make something like this:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
Apparently, in your case it will look like this:
$link = mysqli_connect(WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME);
And then you can continue with your code...
if (!link){
die('Sorry, The site is currently unavailable!');
} else{
// write your SQL here and fetch it
}

Why isn't my PHP connecting to my database or displaying an error?

I am creating a form that will take a person's name and email and see if the email exists in the database already but I can't get the database to be selected. The mysql_error() won't display the error either. Is there something wrong with my code for selecting the database? All it shows is the hardcoded text "Could not select database because" then nothing. I replaced all the variables associated with the database with random fillers so as not to give away my info but everything I have is correct regarding that.
$host = "host";
$user = "user";
$password = "pass";
$database = "db";
$port = xxxx;
$table = "table";
// Create connection
$conn = mysqli_connect($host, $user, $password, $database, $port);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection Successful";
mysqli_select_db($database)
or die("Could not select database because".mysqli_error());
// check if the username is taken
$check = "select email from $table where email = '".$_POST['email']."';";
$qry = mysqli_query($check)
or die ("Could not match data because ".mysqli_error());
$num_rows = mysqli_num_rows($qry);
if ($num_rows != 0) {
echo "Sorry, there the username $username is already taken.";
}
Don't call mysqli_select_db. You've already selected your database with the fourth parameter to mysqli_connect.
You only need to call mysqli_select_db if you want to access a different database after the connection has been established.
Also, Raptor is correct that if you call procedural mysqli_error() you must pass it a connection handle.
For Procedural style mysqli_error(), you must supply the MySQLi DB link as parameter:
mysqli_select_db($database)
or die("Could not select database because" . mysqli_error($conn));
But it's useless to call mysqli_select_db() as you already specified the DB schema in mysqli_connect().
Additionally, your SQL is vulnerable to SQL Injection attack. Always escape the parameter before putting into SQL statement, or use prepared statements.
try this code
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>

Error! Call to undefined function pg_insert()

I am trying to copy an array into a table in the test database. I get this fatal error: Call to undefined function pg_insert() in C:\wamp\www\Lessons\GMS-DB.php on line 31. Can u please help me!
Here is my code:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$database = "test";
// Create server connection
$con = mysql_connect ($servername, $username, $password, $database) or die('cant connect server');
mysql_select_db('test',$con);
// Create database connection
$db_selected = mysql_select_db('test',$con);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
//-----------------------------------------------------------------------
// Specify directory
$dir = 'C:/Users/Desktop/data';
$files1 = scandir($dir);
$data = array_diff($files1, array('.', '..')); //remove the dots or periods
// print_r($data);
// put in a string
$matstring = implode("','",$data);
$matstring="".$matstring."";
$table_name = `test table 1`;
$res = pg_insert ($con , $table_name , $data);
if ($res) {
echo "POST data is successfully logged\n";
} else {
echo "User must have sent wrong inputs\n";
}
?>
You have two different kinds of databases there. One is MySQL and another is PostgreSQL. Your using a mysql database so use a mysql query to insert.
You need to use mysql query
mysql_query("INSERT INTO $table (column_name, column_name2) VALUES('$value', '$value2')");
Also, you are using mysqli syntax to connect to db. In mysql, the syntax is
$con = mysql_connect ($servername, $username, $password);
mysql_select_db('foo', $con);
And I strongly suggest you to use mysqli. Ancient mysql is no longer supported!
Here's the code in MySQLi
$db = new mysqli("host", "user", "password", "database");
$db->query("INSERT INTO $table (column_name, column_name2) VALUES('$value', '$value2')");
When should I use MySQLi instead of MySQL?
MySQLi Query

Create Databases Dynamically with Google Cloud SQL and PHP

I am trying to have a database created for each user that signs up for my web app. This database will be based on a template to store their data.
The problem I'm running into is that Google Could SQL doesn't seem to be creating the Database via PHP and MySQL queries.
Connecting to the Instance works fine and triggers no errors based on this code:
//CLOUD SQL CONNECTION FOR SUBSCRIPTIONS
$hostname = details;
$username = details;
$password = details;
$port = details;
$socket = details;
$connection = new mysqli($hostname, $username, $password, $port, $socket);
// Check Connection
if($connection->connect_error) {
trigger_error('Connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
However, when I go to create a simple database, mysqli fails without an error...:
//Create Database
$username = 'account';
$database = 'sub_'. $username .'_db';
$query = "CREATE DATABASE IF NOT EXISTS `{$database}`;";
if(mysqli_query($connection, $query)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($connection);
}
The output of this is simply: Error creating database:
Am I missing something? How do I create a database in a Cloud SQL instance via PHP? Thanks for any input.
Can anyone confirm that this can actually be done on GAE PHP and Cloud SQL?
It seems the $connection variable was actually NULL despite not throwing an error. This worked for me though:
I connected to an existing database:
//CLOUD SQL CONNECTION FOR SUBSCRIPTIONS
$hostname = details;
$username = details;
$password = details;
$db = details;
$port = details;
$socket = details;
$connection = new mysqli($hostname, $username, $password, $db, $port, $socket);
// Check Connection
if($connection->connect_error) {
trigger_error('Connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
Then I created a new database:
//Create Database
$username = 'account';
$database = 'sub_'. $username .'_db';
$query = "CREATE DATABASE IF NOT EXISTS `{$database}`;";
if(mysqli_query($connection, $query)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($connection);
}
Then used mysqli_select_db() to select the newly created database.
//Select Newly Created DB
mysqli_select_db($connection, $database);

php Insert Query - Why Are There Two Connections to a Database?

In my script I link to a page that connects to my database :
include "connect.php";
connect.php
<?php
error_reporting(E_ERROR);
/* Allows PHP to connect to your database */
// Database Variables
$Host = "myhost";
$User = "username";
$Password = "password";
$DBName = "database";
// Connect to Database
$connect = mysql_connect($Host, $User, $Password)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($DBName)
or die ("Could not connect to database ... \n" . mysql_error ());
?
Then in another script I have an insert query:
include "connect.php";
$Link = mysql_connect($Host, $User, $Password);
$Query = "INSERT INTO mytable VALUES ('0','".mysql_escape_string($forename)."','".mysql_escape_string($surname)."', '".mysql_escape_string($username)."', '".mysql_escape_string($password)."', '".mysql_escape_string($email)."')";
if(mysql_db_query ($DBName, $Query, $Link)) {
$message = "You have successfully registered";
header("Location: register.php?message=".urlencode($message));
} else {
die("Query was: $Query. Error: ".mysql_error($Link));
}
}
}
Why is this necessary :
$Link = mysql_connect($Host, $User, $Password);
Hasn't the connection already been established?
There is no point in doing this, especially as mysql_* functions will assume the last opened connection if none is given.
However, even with two calls to mysql_connect, only one connection is made. From the docs:
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters.
So by default, the existing connection will be returned.

Categories