PDO - 3D000 No database selected - php

I wanted to create a PDO mysql connection. But the execute() function returns false and the errorInfo() returns "No database selected!". But I selected a database.
This is my code:
$array = array("db" => "blogscript", "host" => "localhost", "user" => "root", "pass" => "");
$db = new PDO('mysql:dbname=' . $array['db'] . ';host=' . $array['host'] . '', $array['user'], $array['pass']);
$statement = $db->prepare('
SELECT *
FROM pages
');
$r = $statement->execute();
if ($r === false) {
return $statement->errorInfo();
}
The database "blogscript" existst.

Hard coding the connection with database & host in this order
$db = new PDO('dbname=blogscrip;mysql:host=localhost', root, pass);
Throws exception could not find driver
in the order in documentation
$dbh = new PDO('mysql:host=localhost;dbname=blogscript', root, pass);
Works
Change the order to host & database

Related

Why does the keys of PDO query() result contain tablename?

I connected mysql with PDO like this:
$servername = 'localhost';
$servername = 'localhost';
$dbname = 'atlas';
$table = 'homepage_pv';
$username = 'root';
$password = 'mysql';
$conn = null;
try {
$conn = new PDO(
"mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
)
);
}
catch(PDOException $e) {
echo "connect to mysql failed : " . $e->getMessage();
$conn = null;
exit;
}
$result = $conn->query('SELECT * from homepage_pv')->fetchAll(PDO::FETCH_NAMED);
echo "result=" . json_encode($result);
the result is :
result=[{"homepage_pv.id":"1","homepage_pv.datetime":"2019-08-19 22:56:26"},{"homepage_pv.id":"2","homepage_pv.datetime":"2019-08-19 22:56:28"},{"homepage_pv.id":"3","homepage_pv.datetime":"2019-08-19 23:01:58"}]
The keys contain the table name "homepage_pv" , which is not expected;
But where I create PDO like this :
try {
$conn = new PDO(
"mysql:host=$servername;",
...
);
}
...
$result = $conn->query('SELECT * from atlas.homepage_pv')->fetchAll(PDO::FETCH_NAMED);
echo "result=" . json_encode($result);
the keys in the result do not contain tablename any more, like this:
result=[{"id":"1","datetime":"2019-08-19 22:56:26"},{"id":"2","datetime":"2019-08-19 22:56:28"},{"id":"3","datetime":"2019-08-19 23:01:58"},{"id":"4","datetime":"2019-08-19 23:08:48"}]
In case1 , I specified dbname when creating PDO and leaved out it when doing query;
In case2 , it's is on the contrary;
So what cause it? how can I specify dbname when creating PDO without the keys in result containing tablename?
Use PDO::FETCH_ASSOC in fetchAll(). If you use PDO::FETCH_NAMED it will return with alias name. If alias not present then with the table name. Attaching the doc for your further reference.

sqlite to mysql using php

I have an application that writes it's data to SQLite everyday. I now want to upload this data into my webhost to use. So I have a scheduled sFTP script to upload the .sqlite file to my webhost and then run another scheduled task to run the php code.
I know that I can use SQLite with PDO but all my other data on the host is in MySQL, so I want to keep everything in the MySQL format.
I have tried writing some php code that will read the sqlite file via PDO and then insert into the MySQL table again with PDO. The script will hopefully run on multiple tables to import so using foreach with Key/Values so I do not have to hardcode every single column in each table (about 30 columns per table)
However I have tried various things but just can not seem to find why the above code does not work problem so asking for help from much better minded users. Please view my code.
Thanks
<?php
ini_set('max_execution_time', 480); //480 seconds = 8 minutes
try {
// Connect to MySQL database
$host = '127.0.0.1';
$db = 'coredb';
$user = 'root';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdomysql = new PDO($dsn, $user, $pass, $opt);
// Connect to SQLite database in file
$file_db = new PDO('sqlite:frp.sqlite');
$file_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT * from frp_teamdata';
$stmt = $file_db->prepare($sql);
$stmt->execute();
$sqliteresults = $stmt->fetch(PDO::FETCH_ASSOC);
foreach($sqliteresults as $results){
foreach($results as $key => $value){
$stmt = $pdomysql ->prepare("INSERT INTO frp_teamdata (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $key);
$stmt->bindParam(':value', $value);
$stmt->execute();
}
}
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
Give this a try:
<?php
ini_set('max_execution_time', 480); //480 seconds = 8 minutes
try {
// Connect to MySQL database
$host = '127.0.0.1';
$db = 'coredb';
$user = 'root';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdomysql = new PDO($dsn, $user, $pass, $opt);
// Connect to SQLite database in file
$file_db = new PDO('sqlite:frp.sqlite');
$file_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT * from frp_teamdata';
$stmt = $file_db->prepare($sql);
$stmt->execute();
$sqliteresults = $stmt->fetch(PDO::FETCH_ASSOC);
//Prepare the statement only once!
$stmtmysql = $pdomysql ->prepare("INSERT INTO frp_teamdata (name, value) VALUES (:name, :value)");
//Bind the params only once -- I assume the keys and values are strings
$stmtmysql->bindParam(':name', $key, PDO::PARAM_STR);
$stmtmysql->bindParam(':value', $value, PDO::PARAM_STR);
foreach($sqliteresults as $results){
foreach($results as $key => $value){
$stmtmysql->execute();
}
}
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
Note: I have not tried the code, so let me know if you have any issues.

Error passing mysql connection as parameter

I'm trying to build a basic API with PHP and mysql and depending on the url path, different database tables are used and therefore the connection needs to be made. But I keep getting this error:
Fatal error: Call to a member function prepare() on a non-object
in....line 6
dashboard.class.php:
class dashboard {
public function getData($conn) {
// Get latest status
$stmt = $conn->prepare("SELECT status FROM status_archive ORDER BY datetime DESC LIMIT 1 ");
$stmt->execute(); //line 6
$stmt->bind_result($status);
$stmt->fetch();
($status == '1' ? $status = 'up' : $status = 'down');
$stmt->close();
return $status;
}
}
Function that creates the database connection:
function db_connection($type) {
$db = $type.'_db';
syslog(LOG_INFO, 'DB: '.$db);
// Check to see if a development or production server is being used
if (strpos(getenv('SERVER_SOFTWARE'), 'Development') === false) {
$conn = mysqli_connect(null,
getenv('PRODUCTION_DB_USERNAME'),
getenv('PRODUCTION_DB_PASSWORD'),
$db,
null,
getenv('PRODUCTION_CLOUD_SQL_INSTANCE'));
} else {
$conn = mysqli_connect(getenv('DEVELOPMENT_DB_HOST'),
getenv('DEVELOPMENT_DB_USERNAME'),
getenv('DEVELOPMENT_DB_PASSWORD'),
$db);
}
// Check if successful connection to database
if ($conn->connect_error) {
die("Could not connect to database: $conn->connect_error " .
"[$conn->connect_errno]");
}
return $conn;
}
This is the code at the end of the file that initiates everything:
$path_array = explode("/", parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
$conn = db_connection($path_array[3]);
include 'classes/dashboard.class.php';
$dashboard = new dashboard;
$results = $dashboard->getData($conn);
echo json_encode($results, JSON_PRETTY_PRINT);
mysqli_connect can to return falsy value.
You should use OOP style (new mysqli) or check $conn:
$conn = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (!$conn) {
die('Connection error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
php.net - See "Procedural style" example.
It turned out it was due to variable scope.
I ended up using PHP $GLOBALS to get it to work.

Connect to Multiple Databases using MySQLi

I need to connect to two databases using PHP and use the results from the first query to get the rest of the data I need out of a second database.
So for the second connection, I need to connect to the second database and Select state and zipcode where the results from connection 1 (client) is equal to the firstname in database 2. How would I do this?
<?php
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['cd']) && is_numeric($_GET['cd'])) {
// get id value
$id = intval($_GET['cd']);
}
$results = $id;
//Open a new connection to the MySQL server
require "calendarconnect.php";
//chained PHP functions
$client = $mysqli->query("SELECT client FROM appointments WHERE ID = $results")->fetch_object()->client;
print $client; //output value
$mysqli->close();
Connection To Database Code is similar to the below
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','some database','some password','some username');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
This isn't tested, but I think it would go something like this.
<?php
$dbc1 = new MySQLi()or die('error connecting to database');
$dbc2 = new MySQLi()or die('error connecting to database');
//build query 1
$query1 = "SELECT * FROM Table";
$result1 = $dbc1->query($query) or die("Error in query");
$thing1 = '';
// check result
if($result1->num_rows){
//fetch result as object
$row = $result1->fetch_object();
//set attributes
$thing1 = $row->Name;
}
//build query 2
$query2 = "SELECT * FROM AnotherTable WHERE Id = '$thing1'";
$result2 = $dbc2->query($query) or die("Error in query");
$thing2 = '';
// check result
if($result2->num_rows){
//fetch result as object
$row = $result2->fetch_object();
//set attributes
$thing2 = $row->Name;
}
?>
You would need to make 2 different connections
<?php
$mysqliDB1 = new mysqli('localhost', 'DB1UserId', 'pwd', 'db1');
$mysqliDB2 = new mysqli('localhost', 'DB2UserId', 'pwd', 'db2');
Now when you use the $mysqliDB1->.... you are talking to the DB1 database and when you use the $mysqliDB2->.... you are talking to the DB2 database
So
$client = $mysqliDB1->query("SELECT client FROM appointments WHERE ID = $results")
->fetch_object();
$locn = $mysqliDB2->query("SELECT state,zipcode
FROM location
WHERE ClientID = {$client->FirstName}")
->fetch_object();
echo $locn->state;
echo $locn->zipcode;
I am guessing the table name and so on, but I am not clarevoyant so you will have to fill that in for yourself.
If you want to perform queries in two databases at the same time you need to have two separate mysqli objects. To open the connection you can use the following code:
// Don't forget to enable error reporting!
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db1 = new mysqli('localhost', 'user', 'pass', 'dbName');
$db1->set_charset('utf8mb4'); // always set the charset
$db2 = new mysqli('localhost', 'user', 'pass', 'dbName2');
$db2->set_charset('utf8mb4'); // always set the charset
Then you can perform your two statements in each database separately.
// get id value
$id = intval($_GET['cd']);
// Get client name from DB1
$stmt = $db1->prepare('SELECT client FROM appointments WHERE ID = ?');
$stmt->bind_param('s', $id);
$stmt->execute();
$client = $stmt->get_result()->fetch_object();
// Get state and zipcode from DB2
$stmt = $db2->prepare('SELECT state,zipcode FROM location WHERE ClientName = ?');
$stmt->bind_param('s', $client->client);
$stmt->execute();
$location = $stmt->get_result()->fetch_object();
echo $location->state;
echo $location->zipcode;

how to connect ( pull data ) from one server to ( insert into - create table ) another server using pdo in php-mysql , possibly fetch ?

Can anyone please tell me how could I fix this code below ? so that I can pull data from host1 (database x , table 1 ) to create table in host2 ( database dx, table2 ),
What am I missing here ? someone tell me to use prepare then fetch array then insert into table2 , can any one show me , how to ?
here's my code
<?php
echo 'Database Connection <br>';
$hostname = "host1";
$hostname1 = "host2";
$username = "myname";
$password = "mypassword";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=x", $username, $password);
echo "Connected to database x<br>"; // check for connection
$dbup = new PDO("mysql:host=$hostname1;dbname=dx", $username, $password);
echo "Connected to database dx<br>"; // check for connection
/*** The SQL SELECT statement ***/
$sql = $dbh->query("select name, choices from table1")or die(print_r($dbh->errorInfo(), true));
$sql1 = $dhup->query("CREATE TABLE api(
`name` VARCHAR(40) NOT NULL,
`choices` VARCHAR(255) NOT NULL )")or die(print_r($dbh->errorInfo(), true));
foreach ($sql as $row)
{
$dbup->exec("insert into table2('name','choices') values('" . $row['name'] . "','" . $row['choices'] . "')") or die(print_r($dbup->errorInfo(), true));
}
// /*** close the database connection ***/
$dbh = null;
$dbup = null;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
?>
Thanks
I noticed you're not consistently spelling "dbup" the same way.
In:
$dbup = new PDO...
You used d'B'up.
In:
$dhup->query("CREATE TABLE...
You used d'H'up.
Maybe this is a simple case of a typographical error?

Categories