connecting to phpMyAdmin database with PHP/MySQL - php

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

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"

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

need help traying to access my database with mysql

Just built my first database to test out learning skills using the simple query below:
<?php
mysqli_connect("xxx","yyy","zzz" , "newtone" );
if (mysqli_connect_error()){
echo ("could not connect to database");
}
?>
This is what I got
:(42000/1044): Access denied for user 'yyy'#'xxx' to database 'newtone'......
I don't get it. So When i Use this:
mysqli_connect("xxx","yyy","zzz" );
if (mysqli_connect_error()){
echo ("could not connect to database");
}
?>
I don't get an error message, just a blank page (notice how the database name is not included on the login argument). What am I doing wrong?
You want to connect with database then need three things for create connection dbhost username,dbhost password and your database name.
<?php
$dbhost = "localhost";
$dbuser = "root"; //In case of localhost (default db username)
$dbpass = ""; //In case of localhost
$dbname = "testDb";//Your database name
$con = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname );
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Your 2nd example works because you are successfully connecting to the MySql server, and defaulting to a default database other than "newtone"
If you tried a command like mysqli::select_db after connecting, you would see the same error. http://php.net/manual/en/mysqli.select-db.php
The crux of your problem seems to be permissions for your user yyy. Make sure user yyy has various permissions like read/write on the DB "newtone"

PHP - Connect to Multiple MySQL Databases

So I have a PHP page that connects first to my database and does a bunch of stuff using the information from there. Now I want to connect to another database within the same PHP page and access data from there and insert the information into my original database.
The code:
<?php
session_start();
include ("account.php");
include ("connect.php");
....
do stuff here
....
include ("account2.php");
include ("connect2.php");
...
$thing = "SELECT abc, efg, hij FROM table ORDER BY RAND() LIMIT 1" ;
$thing = mysql_query($thing);
echo "$thing";
....
....
insert information into my database
(From account.php & connect.php files)
....
?>
Everything shows up except for $thing. It says, "Invalid query: Query was empty" but I know the query I used works because when I ran it in the account2 database, I got the results I wanted. Is there something wrong with my logic or is it something else?
You are not mentioning database connection link while executing the query. May be your second database connection is defined after the 1st one in connection.php file. So interpreter is considering 2nd connection while executing the query.
Define the connection link with query,
$thing = mysql_query($thing,$conn); //$conn is your mysql_connect
You can still use the mysql_connect or similar mysql_ functions (procedural way) But all these are now deprecated. You should use mysqli_ (mysql improved) functions or go with the object oriented way.
$conn1 = new mysqli(SERVER1,DB_USER1,DB_PASS1,DB1);
$conn2 = new mysqli(SERVER2,DB_USER2,DB_PASS2,DB2);
if($conn1 ->connect_errno > 0 || $conn2 ->connect_errno > 0){
die('Unable to connect to database server.');
}
Now while executing your query,
$query = "SELECT abc, efg, hij FROM table ORDER BY RAND() LIMIT 1";
$thing = $conn1 -> query($query); //if it's second connection query user $conn2
Many web applications benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.
For your case, i would make 2 persistent connections, store each in it's own variable and then use one whenever i need to. Check it out using the PDO class.
//Connection 1
$dbh1 = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
.
.
.
//Connection 2
$dbh2 = new PDO('mysql:host=localhost;dbname=test2', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
After you finish you first database operation, then you can close the connection using
mysql_close($c) //$c = connection
And again start for next database operation.
private static function _connectDB1()
{
//give hostname, dbusername, dbpassword
$con1 = mysql_connect("localhost", "root", "rootpass");
$db1 = mysql_select_db("dbone", $con1);
}
private static function _connectDB2()
{
//if you are using different db with different credentials
//you can give here like this
// mysql_connect("mynewhost", "mynewusername", "mynewpassword")
$con2 = mysql_connect("localhost", "root", "rootpass");
$db2 = mysql_select_db("dbtwo", $con2);
}

why can't connect to the mysql

one: i using this code to connect mysql databse which on a shared host.
<?php
mysql_connect("localhost", "user", "123") or die(mysql_error());
echo "Connected to MySQL<br />";
?>;
the user and password are created by the cpanel.which are the database's user and password.
two: i use this line mysql -hlocalhost -uuser -p123 in my window operation system MS-DOS window. but it still can't connect the mysql. why?
I think you need to declare a variable. ie $link = mysql_connect("...")...
or you might want to specify which db you want to connect to, the db name.
http://php.net/manual/en/function.mysql-connect.php
mysqli_connect("host_parameter", "user_parameter", "password_parameter, "database_parameter");
$link= mysqli_connect("localhost","root","root_password","my_database");
if(empty($link)){
die("Error:" . mysqli_error());
}
if it's your first time ( mysql user_parameter = root and password = "")
HOPE IT HELP U

Categories