Transition from mysql to PDO - php

I'm in the process to learn PDO. I started changing my database connection from this:
$dbname = "database1";
mysql_connect(
':/Applications/MAMP/tmp/mysql/mysql.sock',
'root',
'root'
) or die( mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
to PDO connection:
$username = "root";
$password = "root";
try {
$conn = new PDO('mysql:host=localhost;dbname=database1', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
the connection seems to be working but when I try to login on the website (localhost) it doesn't find my username and password.
Do I need to change all my mysql_query to PDO since I changed the database connection to PDO?
Can I please ask you some reference for a good tutorial to help me during this transition phase?
thanks

Yes you do.
Here is a good PDO tutorial and this one

Related

Cannot Connect to MySQL with PHP

I have the following code:
<?php
//Step1
$db = mysqli_connect('localhost','root','[mypassword]','users')
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
</body>
</html>
I am just trying to connect to my MySQL database. It is administered using phpMyAdmin. I am very unfamiliar with MySQL and I have never used it before. [mypassword] is the password I use to successfully connect to mySQL from the Mac terminal. "users" is a name of a table I have created in phpMyAdmin. I am using cPanel. I keep on getting the error:
Error connecting to mySQL server.
In phpMyAdmin it says Server: localhost:3306. I have tried for a very long time to fix this problem but with no results. What am I doing wrong?
I have also tried the following:
<?php
$servername = "localhost";
$username = "root";
$password = "[myPassword]";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $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();
}
?>
After visiting the webpage it says
Connection failed: SQLSTATE[28000] [1045] Access denied for user
'root'#'localhost' (using password: YES)
Be sure that your mySql instance is up. You can download sequelpro and use that to connect to your mySQL. If that doesn't work then its a mysql setting/config that is wrong.
You can try this code
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
How to Connect to mysql using php
Use a try catch to handle errors on the connection proccess, but i strongly advise you to use PDO by alternative from mysqli PDO Book
Use something like this:
<?php
try
{
if ($db = mysqli_connect($hostname_db, $username_db, $password_db))
{
//do something
}
else
{
throw new Exception('Unable to connect');
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
And check if the code print some connection error.
Reference: how to use throw exception in mysql database connect

PHP script cannot access database in sql

I am trying to connect to a MySQL database through a php script. It gives me this error from mysql_error(): Access denied for user '#localhost' to database 'userinfo'
userinfo is the database.
my script is this
<?php
$servername = "localhost";
$username = "root";
$password = "'mm'";
$database = "userinfo";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully<br>";
mysql_select_db($database) or die(mysql_error());
echo "connected successfully to db:" . $database . "<br>";
?>
you are connecting using
mysqli_
function
and selecting data with
mysql_
avoid using both at the same time. since they're incompatible.
use the mysqli_ alternative instead
mysqli_select_db($conn, $database);
and
mysqli_error($conn)
Please keep in mind this isn't the safest way. But since you have said your learning this it is a start.
<?php
$servername = "localhost";
$username = "root";
$password = "mm";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
http://www.w3schools.com/php/php_mysql_connect.asp
To select data from the database
http://www.w3schools.com/php/php_mysql_select.asp
It appeared you where combining the old mysql in php with the new mysqli

php syntax database connect

I'm trying to learn this stuff. Please be gentle.
Something is wrong here:
$dbhost = "localhost";
$dbname = "something_dbname";
$dbuser = "something_user";
$dbpass = "pwpwpwpw";
$dberror1 = "Could not connect to the database!";
$dbconnected = "you are connected!";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ($dberror1);
$select_db = mysql_select_db($dbname . $dbconnected) or die ($dberror1);
where is my mistake? I want $dbconnected to show...
I can just as easily use
echo "hello";
it shows that I connect but I'm trying to get familiar with using multiple variables.
would this be better?
$dbhost = "localhost";
$dbname = "something_dbname";
$dbuser = "something_user";
$dbpass = "pwpwpwpw";
$dberror1 = "Could not connect to the database!";
$dbconnected = "you are connected!";
if ($mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname))
echo $dbconnected;
else die($dberror1);
Right now you are trying to connect to a database called something_dbnameyou are connected. The . concatenates variables into one string.
To fix your immediate problem, try this:
First, define $dbhost - I don't see it in your code.
Then change the last line to this:
$select_db = mysql_select_db($dbname) or die ($dberror1);
Then, just echo $dbconnected;
If you are not connected, the page will have called die, and will never reach the line that echos $dbconnected. If you are connected, the program will proceed to this next line and echo your success message.
Or you can do it more explicitly like this:
if ($select_db = mysql_select_db($dbname))
echo $dbconnected;
else die($dberror1);
To fix the bigger problem, DON'T use mysql_*. Read this for more information.
mysqli or pdo are far better options, and you can accomplish the same task easier, for instance, connecting to a db with mysqli is just:
$mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
Or you can do it procedural style, which is closer to your current code. The following snippet is from the php manual, on the page I linked in the comment below.
$link = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($link) . "\n";
mysqli_close($link);
I'd strongly recommend using PDO. The connection string is similar and can be done using:
// I do not see $dbhost defined in your code. Make sure you have it defined first
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo $dbconnected; // will print out the connection success message
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
To answer your question about not using mysql_* functions, you can check out this

MySQL connection error in configuration file

I want to connect to mysql database using php and following is my configuration file.
<?php
$host = "localhost";
$db = "payroll"
$username ="root";
$password = "";
mysql_connect ($host,$username,$password);
mysql_select_db($db,$username);
?>
but when I run my program it gives me this error:
SQL error: No database selected SQL errno: 1046
SQL: select language, admin from user where username='admin' and password='abc123'
What's wrong with my code?
You forgot a semicolon here
$db = "payroll";
^--- Here
Don't forget to enable error reporting on your code. This is how you do it.
This(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. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
Switch to Prepared Statements..
A kickstart example..
<?php
$dsn = 'mysql:dbname=payroll;host=localhost';
$user = 'root';
$password = '';
try
{
$dbh = new PDO($dsn, $user, $password ,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
Read more here on PHP Manual
$mysqlhost="localhost"; // MySQL-Host
$mysqluser="user"; // MySQL-User
$mysqlpwd="password"; // Password
$connection=mysql_connect($mysqlhost, $mysqluser, $mysqlpwd) or die
("CouldnĀ“t connect");
$mysqldb="database"; // Your Database
mysql_select_db($mysqldb, $connection) or die("Couldnt select database");
I always use this. Here you get every errormessage you need to find your error.
Try this
<?php
$host = "localhost";
$db = "payroll"
$username ="root";
$password = "";
$con = mysql_connect ($host,$username,$password);
mysql_select_db($db,$con);
?>

Can't make mysql connection

If I use the following code, it works:
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
But when I do this, it doesn't:
$db_host='localhost';
$db_id='root';
$db_pass='';
$con = mysql_connect($db_host, $db_id, $db_pass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
Trying to swap (") and (').
mysql_ functions are discouraged for new applicationa you are advised to use mysqli or PDO. The following code uses PDO to connect to database.
//dependant on your setup
$host= "localhost";
$username="XXX";
$password="YYY";
$database="ZZZ";
// connect to the database
try {
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
//Remainder of code
}
catch(PDOException $e) {
echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]'). $e->getMessage()."\r\n", FILE_APPEND);//Change file name to suit
}
// close the connection
$dbh = null;
try using a script like this
$db_host = 'localhost';
$db_id = 'root';
$db_pass ='';
$con = mysql_connect ($ db_host, $ db_id, $db_pass) or die ('Could not connect:'. mysql_error ());
That code is fine. Review the error log- the problem has to be external to that code.

Categories