no database selected when opening a php file - php

I'm trying to create a table with php so I could display data from a database in a browser. I'm using apache, php, mysql and phpmyadmin. the php code is fine - all the examples I've seen on various threads show the same thing.
the problem is when I try to open a php file in a browser I get either ' Invalid argument supplied for foreach()' or 'no database selected'. this probably a basic mistake that I'm doing - but I'm a complete beginner. thanks in advance for any help.
php code below:
<?php
include_once('config.inc.php');
try{
$db = new PDO("mysql:dbname=$db_name;host=$db_server", $db_user, $db_pw);
} catch(PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
print "<div><h3>Title</h3>";
print "<table><tr><th>Column_1</a></th><th>Column_2</a></th></tr>";
foreach ($db->query("SELECT sth_one, sth_two FROM the_database") as $a) {
$row="<tr><td>$a[sth_one]</td><td>$a[sth_two]</td></tr>\n";
print $row;
}
print "\n</table></div>\n";
?>

Could you supply an example for what you're doing?
Generally this indicates, that you forgot to specify which database to use, while connecting to the mysql server

I'm not sure but I think I read something about the right sequence of parameters to insert in the constructor.
Try with:
$db = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pw);
or:
$db = new PDO("dbname=$db_name;mysql:host=$db_server", $db_user, $db_pw);
as indicated here: http://php.net/manual/en/pdo.connections.php

Related

How to connect properly to MySQL database?

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.

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.

moving my sql database localhost to live server

i want to move my sql database and i have exported and imported mysql.sql file from localhost to live server and now i m not getting the files and content from that database. what i do ? i did make sure connection to database if fine and successful
here's my page http://shooop23.byethost7.com
<?php
$db = mysqli_connect('','','','');
if(mysqli_connect_errno()){
echo'Database Connection Failed with following errors: '. mysqli_connect_errno();
die();
}
?>
Once you have successfully established a connection to MySQL, you need to perform a query specifying what you want to retrieve and then subsequently retrieve it.
The following example uses mysqli_fetch_row
You should explore the documentation to learn the basics.
$db = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if(mysqli_connect_errno()){
echo'Database connection failed with the following error: '.mysqli_connect_errno();
exit;
}
if ($result = mysqli_query($db, "SELECT MyCol1,MyCol2 FROM MyTable")) {
while ($row = mysqli_fetch_row($result)) {
echo"{$row[0]} - {$row[1]}<br>");
}
mysqli_free_result($result);
}
mysqli_close($db);
$db = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
$sql="SELECT * FROM login";
here i connected and stored my database and set a sql command (which is now a string) into these two veriables.
if(mysqli_connect_errno()){
echo'Database connection failed with the following error: '.mysqli_connect_errno();
exit;
}
this is to check if the database is correctly connected, if not then it will show some errors.
$result = mysqli_query($db,$sql);
here i put the database and the sql command to run my query.
while($row = mysqli_fetch_array($result)){
echo $row['username'];
}
here finally outputting the usernames(username is one of the column in my table in this case) which matched with that query
i will suggest This Sql site to get a better understanding on sql queries and try to improve the secuirty because this is the basic point where hackers try to inject their attact most offenly.
Note : If your table's in the database are empty then it will not able to fetch anything

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;

cannot get a connection to MySQL in php

I have this simple code:
<?php
//Open the mySQL connection
$conn_string = "'localhost', 'Vale', 'test'";
$dbh = mysql_connect($conn_string);
//Check that a connection with the DB has been established
if (!$dbh)
{
die("Error in MySQL connection: " . mysql_error());
}
...
And I get the error: Error in MySQL connection: php_network_getaddresses: getaddrinfo failed: The requested name is valid, but no data of the requested type was found.
I cannot figure out what the problem is, I have been google-ing but all the suggestions have failed (tried 127.0.0.1 instead of localhost, 127.0.0.1:3306, etc.)
I have code that works with postgre, but I need to use mysql, and I am trying to modify it, but I cannot pass the first line and get a connection. Any suggestion, please? Thank you!
mysql_connect doesn't take a comma seperated string. It takes 3 individual strings.
Change it to this:
$dbh = mysql_connect($server, $mysql_user, $password);
If you absolutely have a comma separated string, and can't get around this, you can split the string like this:
$config = str_replace("'", '', $conn_string); // replace the quotes.
$config = preg_split('/,/', $conn_string); // split string on ,
if($config != $conn_string) { // make sure this returned an array
count($config) === 3 OR die("Invalid database configuration string");
$dbh = mysql_connect($config[0], $config[1], $config[2]);
if(FALSE === $dbh) {
die("Coult not connect: " . mysql_error());
}
}
You might want to consider MySQLi, instead of MySQL.
<?php
$dbh=mysqli_connect("localhost","Vale","Password","test"); /* Vale is your username? And the name of your database if test, right? And your Username's Password is blank? */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
As other users have pointed out mysql_connect expects the database, username, and password as separate arguments rather than a single string.
I think another highly important issue to point out is that this particular extension is deprecated.
Please see: http://uk1.php.net/function.mysql-connect
A better solution would be to use mysqli_connect: http://uk1.php.net/manual/en/function.mysqli-connect.php
$db = mysqli_connect( 'localhost', 'Vale', 'test', 'yourDatabaseName' );
mysql_connect requires three argument not single string
$dbh = mysql_connect('localhost', 'Vale', 'test');

Categories