How to create database in Yii2 format - yii2

I want create database with yii2.
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
With this code we can create DB but i want to know whether it is possible in Yii2 manner

Currently there is no way you can do it with Yii2. It is because too much complexity for a framework to have everything works on many database engines (MySQL, Oracle, MSSQL, etc). Too many efforts to code, yet the functionality can be done using your query.
IMO, there is nothing wrong with creating a database using current db connection. This can be found in SaaS multi-tenant architecture, when a new client registers an account, then a new separated DB created to encapsulate mostly everything / security reason.

It's not recommended to create tables at run-time. Already set-up the schema and run your SQL / non-SQL query.
For this, you need to create a file (say myDB.php) in your config folder and provide database details as follows :
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'dblib:host=localhost;dbname=yourDBName',
'username' => 'yourUsername',
'password' => 'yourPassword',
'charset' => 'utf8',
];
Register this database in your web.php.Add following line :
'my_db' => require(__DIR__ . '/myDB.php'),
In controller, use this db as follows :
$query = 'select columnID from table where ID=:ID';
Yii::$app->my_db->createCommand($query)
->bindValue(':ID',1)
->queryOne();

Related

Connecting to remote mysql server using sequelize [duplicate]

I have Xampp installed in windows and I am creating an application using Laravel 5.3. I am trying to execute a query on another server on local network but when I try to do that the MySql server authenticate the user that is on my local server with is (username: "root" && password:"") while the remote server have (username: "root" && password:"root") and i don't know why. here is my laravel connection under config/database.php
'smsgateway' => [
'driver' => 'mysql',
'host' => '**.**.**.**',
'database' => 'database',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
how i use the connection
$smsgateway = \DB::connection('smsgateway');
// dd($smsgateway);
$smsgateway->statement($sql);
I tried to connect using a native PHP code but I face the same problem here is my code
$servername = "**.**.**.**;
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
it gives me
Connection failed: SQLSTATE[HY000] [1045] Access denied for user
'root'#'myIPAddress' (using password: YES)
You need to grant the permission to access the database from local
Use these commands and then revert , help url here
grant remote access of MySQL database from any IP address
In my own case, due to valid security concerns, i opted to develop an API to connect to the remote mysql database. I did this using php's CURL library. On the foreign domain (the domain you are connecting from), i did a curl post to the database domain (the domain holding the database).
From here its quite easy as all you do is save the $_POST parameters using prepared statements on the local database. I just thought to put this answer here. It might help someone out there
For example, you would like to save two values to the remote database.
<?php
$array = array('key1' => $key1, 'key2' => $key2);
$url = 'www.site.com/api.php';
#do curl post to remote database
$ch = curl_init();
if ($ch !== false) {
curl_setopt($ch, CURLOPT_URL, $url); //this is the url of the domain where the database is being hosted
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json')); //if you are returning json
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
#on the #url script, all you do is access the values via `$_POST`. example: `$_POST['key1'];`
?>
Don't use root in password. Password field should be blank on your XAMPP set up.

I cant connect to my MYSQL Database using Php

Hi i have a problem connecting with my Mysql database i have the following code:
<?php
$servername = "dt5.ehb.be";
$username = "TVOSAPP";
$password = "*****";
$dbname = "TVOSAPP";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT storyId, title, score FROM Stories";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["storyId"]. "Naam" . $row["title"]. "score" . $row["score"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
which gives the following error:
Connection failed: Access denied for user 'TVOSAPP'#'10.3.101.30' (using password: YES)
I hope you can help me out to solve this problem it would be very much appreciated
the user that you are trying to connect with might not have the permission to connect remotely to the DB. please verify the same. To give remote access you might need to run
grant <privilage name> on TVOSAPP.* to 'TVOSAPP'#'<youripaddress>' identified by <yourpassword>
Ref: http://dev.mysql.com/doc/refman/5.7/en/grant.html
EDIT:
If your IP address is not static then you can use a percentage sign (%) in place of your IP address. However this approach is less secure as it allows any host to connect to the database remotely.
I fixed it about a week ago is had a space too much thats why I couldn't connect thank you all for your responses

AWS - RDS database connection returns no error but a white page

I am trying to connect my EC2 instances to a RDS mysql database.
In my DB class I do this:
private function __construct() {
$dbhost = "xxxxxxxxx.xxxxxxxxx.us-west-2.rds.amazonaws.com";
$dbport = "3306";
$dbname = "mydatabase";
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname}";
$username = "myUsername";
$password = "myPassword";
try {
$this->_pdo = new PDO($dsn, $username, $password);
$this->_pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOExeption $e) {
die($e->getMessage());
}
}
When I tried to query the database I don't get any error but a white screen even though I turned the error reporting on:
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
The inbound traffic on the security group is wide open:
and both the RDS and the EC2 instance are on the same VPC (the default one).
Please note the code is working with my current database.
The problem was not in the connection but my query was returning rows that had a single quote (ie. Men’s) so that caused the problem to json encode. I fixed it adding SET NAMES utf8:
$this->_pdo = new PDO($dsn, $username, $password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));

How to solve mysql close warning

I have tried
this code-
$query=mysql_query("insert into ims(emp_name,emp_id,department,subject,date,matter)
value('".$_SESSION['name']."','".$_SESSION['eid']."','".$_SESSION['dept']."','".$_POST['subject']."','".$_POST['date01']."','".$_POST['textarea2']."')") or die("Inenatry Error");
<?php mysql_close($query);?>
I got error:
Warning: mysql_close(): supplied resource is not a valid MySQL-Link resource in
mysql_close() accepts a connection resource as parameter
Suppose you have your connection like this
$connection = mysql_connect(...);
then use
mysql_close($connection);
For more information see this.
Warning : mysql_* is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used
you have to do something like
$db_conn = mysql_connect("localhost", "root", "******");
mysql_close($db_conn);
Well, you'd have to show us this line. Generally, though, using mysql_close() isn't needed - the connection is automatically closed when the script has finished executing.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
You are doing it wrong. mysql_close will take mysql connection resource not query object. So your code should like that.
$conn = mysql_connect('DB_HOST', 'DB_USER', 'DB_PASS');
mysql_select_db('DB_NAME');
$query = mysql_query("insert into ims(emp_name,emp_id,department,subject,date,matter) value('".$_SESSION['name']."','".$_SESSION['eid']."','".$_SESSION['dept']."','".$_POST['subject']."','".$_POST['date01']."','".$_POST['textarea2']."')") or die("Inenatry Error");
mysql_close($conn);

Uploading MySQL database to server?

I have created a website that has a MySQL database. I'm using phpmyadmin and xampp. Now I have a website to upload the files to (using Filezilla). How do I upload the MySQL database to the server and connect it to the website? I'm guessing there is already a tutorial somewhere but I couldn't find it.
If you have your database file ready to upload then in phpmyadmin there is an import option as shown in the image below:
In order to connect it to your website will depend on your server side language choice...
Example with PHP to connect your website to your database (using pdo):
<?php
$dsn = 'mysql:dbname=name_here;host=127.0.0.1';
$user = 'root'; //change to your username
$password = '******'; //change to your password
try {
$pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
Once you have that at top of your PHP file you can connect. This one way to do it via PHP.