I'm following this tutorial, I'm currently around minute 04:00 and I want to make a connection with my MySQL database through PDO. But my webpage will always give "Could not connect." when I'm trying to make the connection.
When I used PHPStorms inside Database program, I had to change my serverTimezone to Europe/Amsterdam and then I was able to connect to my db.
I tried to add the port number in the 'new PDO()' code.
I tried to change the timezone in the code and on my MySQL server but it gives this error;
mysql> SET GLOBAL time_zone = 'Europe/Amsterdam';
ERROR 1298 (HY000): Unknown or incorrect time zone: 'Europe/Amsterdam'
<?php
try {
$pdo = new PDO('mysql:host=localhost:dbname=mytodo', 'root', '');
} catch (PDOException $e) {
die('Could not connect.');
}
$statement = $pdo->prepare('select * from todos');
$statement->execute();
var_dump($statement->fetchAll());
require 'index.view.php';
Extra information:
mysql> SELECT ##global.time_zone, ##session.time_zone;
+--------------------+---------------------+
| ##global.time_zone | ##session.time_zone |
+--------------------+---------------------+
| SYSTEM | SYSTEM |
+--------------------+---------------------+
The tutorial you are following is very outdated.
A code connecting to PDO has to follow certain rules explained in my article How to connect to MySQL with PDO. In brief
it should configure error reporting mode
it should set the connection charset, the right way
it shouldn't catch it's own errors to report them
it should follow correct DSN syntax, without any extra decorations
it also coud set a couple useful settings
So the code should be like this
$host = '127.0.0.1';
$db = 'mytodo';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$pdo = new \PDO($dsn, $user, $pass, $options);
Here you can see the proper connection code that does a lot of things. Among them, it tells you what the actual problem is when your code cannot connect to database.
You have error in code near localhost
Use semicolon in place of colon
Write this instead:
$pdo=new PDO('mysql:host=localhost;dbname=mytodo','root','');
Related
I'm following this tutorial, I'm currently around minute 04:00 and I want to make a connection with my MySQL database through PDO. But my webpage will always give "Could not connect." when I'm trying to make the connection.
When I used PHPStorms inside Database program, I had to change my serverTimezone to Europe/Amsterdam and then I was able to connect to my db.
I tried to add the port number in the 'new PDO()' code.
I tried to change the timezone in the code and on my MySQL server but it gives this error;
mysql> SET GLOBAL time_zone = 'Europe/Amsterdam';
ERROR 1298 (HY000): Unknown or incorrect time zone: 'Europe/Amsterdam'
<?php
try {
$pdo = new PDO('mysql:host=localhost:dbname=mytodo', 'root', '');
} catch (PDOException $e) {
die('Could not connect.');
}
$statement = $pdo->prepare('select * from todos');
$statement->execute();
var_dump($statement->fetchAll());
require 'index.view.php';
Extra information:
mysql> SELECT ##global.time_zone, ##session.time_zone;
+--------------------+---------------------+
| ##global.time_zone | ##session.time_zone |
+--------------------+---------------------+
| SYSTEM | SYSTEM |
+--------------------+---------------------+
The tutorial you are following is very outdated.
A code connecting to PDO has to follow certain rules explained in my article How to connect to MySQL with PDO. In brief
it should configure error reporting mode
it should set the connection charset, the right way
it shouldn't catch it's own errors to report them
it should follow correct DSN syntax, without any extra decorations
it also coud set a couple useful settings
So the code should be like this
$host = '127.0.0.1';
$db = 'mytodo';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$pdo = new \PDO($dsn, $user, $pass, $options);
Here you can see the proper connection code that does a lot of things. Among them, it tells you what the actual problem is when your code cannot connect to database.
You have error in code near localhost
Use semicolon in place of colon
Write this instead:
$pdo=new PDO('mysql:host=localhost;dbname=mytodo','root','');
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"
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 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
I want to wean myself from the teat of the old mysql extension and am just doing a test PDO connection and simple query on a table in a database. I seem to be able to connect, ('connection successful' echoes out) but that's where the good times end. I have spent way too much time now just trying to get started with PDO.
<?php
$host = 'localhost';
$port = '3306';
$username = 'user';
$password = 'blabla';
$database = 'workslist';
try {
$db = new PDO("mysql:host=$host; port = $port; dbname = $database", $username, $password);
echo 'connection successful<br />';
$query = 'SELECT * FROM main';
$statement = $db->prepare($query);
$statement->execute();
$results = $statement->fetchAll();
$statement->closeCursor();
foreach($results as $r){
echo $r['work'] . '<br />';
}
} catch (PDOException $e) {
echo 'Error!: ' . $e->getMessage() . '<br />';
die();
}
?>
Is there anything wrong with the above?
The database name is 'workslist', the table name is 'main', and 'work' is one of the columns in that table. The PHP version I'm using is 5.3.4, and am using wamp on win7. I ran phpinfo() and under the PDO heading, the PDO drivers mysql, sqlite are enabled. To be sure the database and table actually exist I've tried it with MySQL and can return rows with the old mysql_fetch_array() method. I've checked the php.ini file to make sure the "extension=php_pdo..." lines are all uncommented.
cheers
This should work.
Please double-check that you actually have a table named "main" in that database.
Note that this error will not be discovered by PDO until you execute() the query, and if there is a problem with your query the default behavior is to return an empty result, not throw an exception.
To make PDO noisier, add the PDO::ERRMODE_EXCEPTION option when constructing PDO:
$db = new PDO("mysql:host=$host;port=$port;dbname=$database", $username, $password,
array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION)
);
Now check if you see the following:
Error!: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'workslist.main' doesn't exist
The particular problem is that spaces aren't allowed in the DSN string. With the spaces, the "dbname" directive isn't processed, so there's no default database. Besides removing the spaces, explicitly specifying the database in the statement can help prevent this sort of problem:
SELECT `work` FROM `workslist`.`main`
That way, should there not be a default database for some reason, the query will still succeed.
PDO won't throw an error unless you configure it to:
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );