SQLite3 multithread at same server - php

How can I perform a SQLite3 exec at the same time in PHP?
I have this code (by example):
$bd = new SQLite3("database.db");
$bd->busyTimeout(5000);
$bd->exec("INSERT into 'foo' ('data') values ('bar')");
$bd->close();
unset($bd);
And it works, but the real problem is when I connect another computer to my server and I made the insert at the same time (really, I press the key that trigger the code at the same time in both computers) and it show an error "database is locked".
I know that with the pragma WAL the database works in multithread, but it even show the error. Thank you a lot! and sorry for my bad english.

The problem is sqlite3 employs database locking, as opposed to row or column locking like mysql or postgresql. If you want to do two things at the same time try using mysql, or postgresql. In mysql you would have to create the database. Your code would then look something like this:
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $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();
}
$count = $conn->exec("INSERT into 'foo' ('data') values ('bar')");
$conn = null // close connection

Related

PDO is unable to fetch database name on SQL queries

I am trying to connect to the database via PDO and my db.php file is as follows:
$host = "localhost";
$db = "mydb";
$user = "user";
$pass = "qRES2fIWK8Gg";
try
{
$db = new PDO("mysql:host = $host; dbname = $db", $user, $pass);
$db -> exec ("SET NAMES utf8"); // charset = utf8 doesn't work.
echo "Database connection is successful. <br>";
}
catch (PDOException $e)
{
echo $e -> getMessage();
}
I have two problems which I think there is a connection between them.
When I check the db.php, I can get Database connection is successful message even though I change the host and dbname with random and incorrect values. How is that possible? When I try the same process on the database username and password, it gives an error.
I am unable to run SQL queries without stating database name in it as PDO
doesn't fetch database name from db.php. For example, this SQL query
doesn't work:
SELECT * FROM settings WHERE settings_id= :id
However, this one works successfully:
SELECT * FROM mydb.settings WHERE settings_id= :id
I was working on localhost. After this problem, I thought it has been related to localhost and I moved my project to a virtual host. However, this step hasn't fixed the problems.
Removing the spaces in your DSN string should resolve your issues:
"mysql:host=$host;dbname=$db"

Why I'm not able to create a new database in MySQL using PDO? Is it necessary to have a database already present before creating a new one using PDO? [duplicate]

This question already has answers here:
Pdo connection without database name?
(4 answers)
Closed 5 years ago.
I've installed the latest available version of XAMPP Package on my machine running on Windows 10 Home Single Language Edition.
I'm learning PHP and MySQL.
So, first of all in order to create a new database I wrote following code :
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();//Getting 'Notice : Undefined variable : sql' for this line
}
$conn = null;
?>
The database didn't get created and I received following error in output after running above file in a web browser :
Notice: Undefined variable: sql in prog_1.php on line 16
SQLSTATE[HY000] [1049] Unknown database 'mydb'
Can someone please help me by correcting my code, so that I can further start studying the database concepts in actual manner?
Is it necessary to have a database already present when accessing the same using PDO?
P.S. : The database titled 'mydb' is currently not present in MySQL RDBMS.
You're setting the DB name in your DSN connection string, and it looks like mydb doesn't exists.
Just remove that part from the DSN string and try again.
Your $conn = new PDO() fails because there isn't a database called myDB (SQLSTATE[HY000] [1049]). Because that line fails your try catch statement will evaluate to the catch part before it declares the $sql variable. So when you try to access the $sql variable in the catch part it does not exist and will throw an Undefined variable error.
You'll have to move the $sql above the $conn = new PDO() line to fix the undefined variable error. To fix the missing database error you'll have to create a database called myDB.
try {
$sql = "CREATE DATABASE myDBPDO"; // moved it here
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// (...)
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage(); // no undefined variable
}
To connect to the database without selecting a specific database you'll have to change your new PDO() DSN to this:
$conn = new PDO("mysql:host=$servername", $username, $password);
For more information please check this answer.

SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected

I am trying to insert data into one of the 3 tables in a database using PDOs. When I call the insert function below, and get the error: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected.
Probably going out on a limb here.
It seems to me that you haven't created any of the variables/arrays for your connection, or is not configured correctly. (Not enough code posted in your question).
From the manual on PDO connection http://php.net/manual/en/pdo.connections.php
Example #1 Connecting to MySQL
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>
Example #2 Handling connection errors
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Plus, looking at the "image of" your code, it looks to me like you are using regular quotes around your columns, rather than ticks. Those are two different animals altogether.
INSERT INTO Students ('RIN', 'First Name', 'Last Name' ...
and having spaces between words, where yes; ticks must be used.
Therefore, you need to modify your code to read as
INSERT INTO Students (`RIN`, `First Name`, `Last Name` ...
and changing the quotes to ticks as outlined above for all the other column names. I wasn't going to type everything out here.
You also need to check for errors with exceptions in the DSN. Using what you have now, isn't enough.
http://php.net/manual/en/pdo.error-handling.php
Example #1 Create a PDO instance and set the error mode
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Make sure that you chose (and created) the right database/table and that you did in fact create all those columns and using the right types and lengths.
If you get errors for something that MySQL may complain about (such as apostrophes), then you will need to escape your data; something you should be doing anyway.
Consult the following, and use a prepared statement:
http://php.net/manual/en/pdo.prepared-statements.php
In your code I didn't see where or when you selected the db. see this for more info.
But to be clear this is what I', referring to
$conn = new mysqli($servername, $username, $password, $dbname);
as you can see the last variable is the dbname.

Simple PDO write not working

I'm trying to get a simple PDO insert to work. I have successfully created a tabled named mydb10 using PDO, and the next part I want to do is insert data into that table. Running the script does not return any errors (PDO error mode exception is enabled), but the table still contains null values.
I'm using a local server to run the PHP file, and am connecting to an Amazon RDS database. Currently all inbound traffic through SSH, HTTP, HTTPS, and MYSQL is allowed through the database's security group
$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$username,$password);
$statement = $link->prepare("INSERT INTO mydb10 (selectedMain, selectedSide)
VALUES(:selectedMain, :selectedSide)");
$statement->execute(array(
"selectedMain" => "test",
"selectedSide" => "test2"
));
This might be silly, but I've been stuck for a while now and any help is appreciated. If you'd like any more information, let me know. I'm trying to utilize PHP in my app, but can't even get this simple test to work, so it's a bit discouraging.
EDIT # 1
This snippet is part of a larger file. I am able to successfully
connect to the database with my credentials and create new tables on the server. I do have PDO error reporting enabled in exception mode, and it has helped me work past syntax errors, but I am no longer getting any errors when I run the code. There are also no errors on the MYSQL server log.
I can provide any additional information that may be useful in debugging if desired.
First you need to properly set connection to MySQL database. You can write this code to sql.php:
<?php
$ServerName = "******";
$Username = "******";
$Password = "******";
$DataBase = "******";
try {
$CONN = new PDO("mysql:host=$ServerName; dbname=$DataBase", $Username, $Password);
$CONN->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Now, when you properly set connection, you need to execute sql, but before this you need to include sql.php:
try {
$SQL = 'INSERT INTO MyDB10 (SelectedMain, SelectedSide) VALUES(:SelectedMain, :SelectedSide)'; // Write SQL Query to variable
$SQL = $CONN->prepare($SQL); // Prepare SQL Query
$SQL->execute(array('SelectedMain' => 'Test', 'SelectedSide' => 'Test2')); // Execute data to Insert in MySQL Databse
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
When you finish all queries you must close connection with:
$CONN = null;

How do I select a MySQL database to use with PDO in PHP?

I want to select a MySQL database to use after a PHP PDO object has already been created. How do I do this?
// create PDO object and connect to MySQL
$dbh = new PDO( 'mysql:host=localhost;', 'name', 'pass' );
// create a database named 'database_name'
// select the database we just created ( this does not work )
$dbh->select_db( 'database_name' );
Is there a PDO equivalent to mysqli::select_db?
Perhaps I'm trying to use PDO improperly? Please help or explain.
EDIT
Should I not be using PDO to create new databases? I understand that the majority of benefits from using PDO are lost on a rarely used operation that does not insert data like CREATE DATABASE, but it seems strange to have to use a different connection to create the database, then create a PDO connection to make other calls.
Typically you would specify the database in the DSN when you connect. But if you're creating a new database, obviously you can't specify that database the DSN before you create it.
You can change your default database with the USE statement:
$dbh = new PDO("mysql:host=...;dbname=mysql", ...);
$dbh->query("create database newdatabase");
$dbh->query("use newdatabase");
Subsequent CREATE TABLE statements will be created in your newdatabase.
Re comment from #Mike:
When you switch databases like that it appears to force PDO to emulate prepared statements. Setting PDO::ATTR_EMULATE_PREPARES to false and then trying to use another database will fail.
I just did some tests and I don't see that happening. Changing the database only happens on the server, and it does not change anything about PDO's configuration in the client. Here's an example:
<?php
// connect to database
try {
$pdo = new PDO('mysql:host=huey;dbname=test', 'root', 'root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $err) {
die($err->getMessage());
}
$stmt = $pdo->prepare("select * from foo WHERE i = :i");
$result = $stmt->execute(array("i"=>123));
print_r($stmt->fetchAll(PDO::FETCH_ASSOC));
$pdo->exec("use test2");
$stmt = $pdo->prepare("select * from foo2 WHERE i = :i AND i = :i");
$result = $stmt->execute(array("i"=>456));
print_r($stmt->fetchAll(PDO::FETCH_ASSOC));
If what you're saying is true, then this should work without error. PDO can use a given named parameter more than once only if PDO::ATTR_EMULATE_PREPARES is true. So if you're saying that this attribute is set to true as a side effect of changing databases, then it should work.
But it doesn't work -- it gets an error "Invalid parameter number" which indicates that non-emulated prepared statements remains in effect.
You should be setting the database when you create the PDO object. An example (from here)
<?php
$hostname = "localhost";
$username = "your_username";
$password = "your_password";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
echo "Connected to database"; // check for connection
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Alternatively, you can select a MySQL database to use after a PHP PDO object has already been created as below:
With USE STATEMENT. But remember here USE STATEMENT is mysql command
try
{
$conn = new PDO("mysql:host=$servername;", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("use databasename");
//application logic
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
I hope my code is helpful for requested
As far as I know, you have to create a new object for each connection. You can always extend the PDO class with a method which connects to multiple databases. And then use it as you like:
public function pickDatabase($db) {
if($db == 'main') {
return $this->db['main']; //instance of PDO object
else
return $this->db['secondary']; //another instance of PDO object
}
and use it like $yourclass->pickDatabase('main')->fetchAll('your stuff');

Categories