PDO is unable to fetch database name on SQL queries - php

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"

Related

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;

SQLite3 multithread at same server

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

Error message: Database Query failed

For some reason, the following code inside the query works in my MySQL command console, yet when I try to run it as a Query in PHP, something keeps going wrong and I'm not sure what. Here is the code I've done so far.
//2. Perform database query
$query = "SELECT skills.element_id, content_model_reference.element_id, element_name FROM skills, content_model_reference WHERE (skills.element_id = content_model_reference.element_id)";
$result = mysql_query($query);
//Tests if there was a query error
if(!$result){
die("Database query failed.");
}
Is there something preventing the code that worked in MySQL (The line with SELECT) from working, or is my syntax somehow wrong?
EDIT: So it's saying I didn't select a database. Yet I thought I had. Here is the code above it:
//1. Create a database connection
$dbhost = "host"; //Host: Can be either an IP address, or a domain (like google.com).
$dbuser = "user";//User: The user that is connecting to the database.
$dbpass = "pass";//Password: This is the password that the user is using.
$dbname = "db";//Name: This is the name of the database.
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);//The value, 'handle,' is the connection.
//Test if connection occurred. Die ends the program/php, and in this case, also prints a message
if(mysqli_connect_errno()){
die("Database connection failed: ".
mysqli_connect_error().
" (". mysqli_connect_errno() . ")"
);
}
Like I said, the error message I am getting is pertaining only to the query, the server is fine with my database connection.
You're using mysqli_* for the connection, but you're using mysql_* for the QUERY... don't think you can do that, has to be one or the other (MYSQLI_ preffered). Also the query should be:
$result = mysqli_query($connection,$query);

PHP PDO - can connect but query not working

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

connecting to phpMyAdmin database with PHP/MySQL

I've made a database using phpMyAdmin , now I want to make a register form for my site where peaple can register .I know how to work with input tags in HTML and I know how to insert data into a database but my problem is that I don't know how I can connect to the database that is already made in phpMyAdmin.
The database is a MySQL database, not a phpMyAdmin database. phpMyAdmin is only PHP code that connects to the DB.
mysql_connect('localhost', 'username', 'password') or die (mysql_error());
mysql_select_database('db_name') or die (mysql_error());
// now you are connected
Connect to MySQL
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Also mysqli_connect() function to open a new connection to the MySQL server.
<?php
// Create connection
$con=mysqli_connect(host,username,password,dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Set up a user, a host the user is allowed to talk to MySQL by using (e.g. localhost), grant that user adequate permissions to do what they need with the database .. and presto.
The user will need basic CRUD privileges to start, that's sufficient to store data received from a form. The rest of the permissions are self explanatory, i.e. permission to alter tables, etc. Give the user no more, no less power than it needs to do its work.
This (mysql_connect, mysql_...) extension 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. (ref: http://php.net/manual/en/function.mysql-connect.php)
Object Oriented:
$mysqli = new mysqli("host", "user", "password");
$mysqli->select_db("db");
Procedural:
$link = mysqli_connect("host","user","password") or die(mysqli_error($link));
mysqli_select_db($link, "db");
$db = new mysqli('Server_Name', 'Name', 'password', 'database_name');

Categories