How to connect properly to MySQL database? - php

I'm trying to connect MySQL to my PHP program. The database was properly connected as it doesn't show any error messages with database connection. But when I'm trying to fetch data from the table, the output doesn't show any outputs. It leaves a blank screen. No error messages are also shown. It displays only 'Database connected successfully'.
<?php
define('user', 'root');
define('pwd', '');
$dsn = "mysql:host=localhost:3307;db_name=mydatabase";
try{
$db = new PDO($dsn,user,pwd);
echo "Database connected successfully";
$query = "SELECT * FROM student_detail";
$statementss = $db->prepare($query);
$statementss->execute();
$detail = $statementss->fetchAll();
foreach ($detail as $student) {
echo $student['Name']." ";
echo $student['Address']." ";
echo $student['Age']." ";
echo $student['Phone']." ";
echo "<br>";
}
$statementss->closeCursor();
}
catch(Exception $e){
echo $e->getMessage()."<br>";
}
?>

It's unclear whether you actually have any values in the database, but I will now explain how to connect properly to MySQL database using PDO extension in PHP.
There are 3 things you need to do always when opening DB connection:
Enable error reporting. In PDO you can pass $options array containing \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION to enable error reporting.
Set the correct charset. The most common one is utf8mb4. If you are using utf8 I strongly recommend to make the switch as soon as possible.
Create an instance of PDO.
You should only catch exceptions if you know why you need to do it. Don't wrap everything in try-catch; this is a terrible idea. Especially don't ever catch exceptions just to echo the error message out; this is pointless. You can however wrap the new PDO(); line in try-catch and then throw a custom exception in catch block if you are paranoid about security.
The name of key-value pair for database name is dbname instead of db_name. Also, when specifying port, there is a separate key-value pair in DSN dedicated to it. It could be that your issue was because you were connecting on the wrong port or because the db_name was not recognized.
Your fixed code would look like this:
<?php
define('user', 'root');
define('pwd', '');
$dsn = "mysql:host=localhost;port=3307;dbname=mydatabase;charset=utf8mb4";
$db = new \PDO($dsn, user, pwd, [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false,
]);
echo "Database connected successfully";
$query = "SELECT * FROM student_detail";
$statementss = $db->prepare($query);
$statementss->execute();
$detail = $statementss->fetchAll();
foreach ($detail as $student) {
echo $student['Name']." ";
echo $student['Address']." ";
echo $student['Age']." ";
echo $student['Phone']." ";
echo "<br>";
}
Unrelated issues:
You probably don't need closeCursor(). I am not sure what the idea of it was in your example.
It's always good idea to separate your database logic from your HTML. Use classes or functions to encapsulate the DB operations and then have the foreach loop in HTML.
The convention for constant naming in PHP is that they should be written in uppercase, so it is easier to distinguish them.
It's recommended to switch off emulated prepared statements. You can add \PDO::ATTR_EMULATE_PREPARES => false to the $options array.

Related

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;

unable to ceil array

I'm trying to do a pagination page with this tutorial, but keep getting errors.
Here is my code:
<?php include "common.php"; ?>
<?php
$query = "SELECT COUNT(id) FROM actiongame";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
foreach($rows as $row):
$total_records = $row;print_r($total_records);
//just to see what is the $total_records
// i get this reult with print_r : Array ( [COUNT(id)] => 2969 )
$total_pages = ceil($total_records / 48);
//but i get fatal error = =
//Fatal error: Unsupported operand types in C:\wamp\www\category.php on line
print_r($total_pages);
endforeach;
unset($row);
?>
My question is, how do I set the $total_records
to 2969 and use the ceil($total_record / 48)?
Here is my db connect script common.php code:
// These variables define the connection information for your MySQL database
$username = 'root';
$password = '';
$host = 'localhost';
$dbname = 'minigame';
// UTF-8 is a character encoding scheme that allows you to conveniently store
// a wide varienty of special characters, like ¢ or €, in your database.
// By passing the following $options array to the database connection code we
// are telling the MySQL server that we want to communicate with it using UTF-8
// See Wikipedia for more information on UTF-8:
// http://en.wikipedia.org/wiki/UTF-8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// A try/catch statement is a common method of error handling in object oriented code.
// First, PHP executes the code within the try block. If at any time it encounters an
// error while executing that code, it stops immediately and jumps down to the
// catch block. For more detailed information on exceptions and try/catch blocks:
// http://us2.php.net/manual/en/language.exceptions.php
try
{
// This statement opens a connection to your database using the PDO library
// PDO is designed to provide a flexible interface between PHP and many
// different types of database servers. For more information on PDO:
// http://us2.php.net/manual/en/class.pdo.php
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// If an error occurs while opening a connection to your database, it will
// be trapped here. The script will output an error and stop executing.
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code
// (like your database username and password).
die("Failed to connect to the database: " . $ex->getMessage());
}
// This statement configures PDO to throw an exception when it encounters
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This statement configures PDO to return database rows from your database using an associative
// array. This means the array will have string indexes, where the string value
// represents the name of the column in your database.
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// This block of code is used to undo magic quotes. Magic quotes are a terrible
// feature that was removed from PHP as of PHP 5.4. However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to
// prevent them from causing problems. For more information on magic quotes:
// http://php.net/manual/en/security.magicquotes.php
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
You're trying to ceil an array, you can do it on a numeric value.
Try editing your query like this:
$query = "SELECT COUNT(id) AS tot FROM actiongame";
And then your PHP code like this:
$total_records = $row['tot'];

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

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

Categories