This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 5 years ago.
I'm a php beginner. I saw many videos in youtube, where they are using mysql instead of mysqli; My editor is NetBeans and Netbeans warns me the mysql is deprecated.
$conn = new mysqli($servername, $username, $password);
My doubt:
Should i learn mysql format or just skip that?
Dont learn the mysql_* functions. Even if you stumble accross them in legacy code its not hard to understand them.
As you already said by yourself, mysql_* functions are deprecated (as of PHP 5.5) and even removed (as of PHP 7).
Also, MySQLi is much more secure because it supports prepared statements.
If you dont want to use MySQLi, you can also use PDO instead.
PDO: http://php.net/manual/en/book.pdo.php
Prepared Statement: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Definitely skip it. Using depreciated technologies is never a good idea especially in a production environment. mysqli and pdo
are better and much safer solutions. PDO is my personal fav ;). Here is a connection to get you started.
<?php
define("DSN", "mysql:host=localhost;dbname=db_name");
define("USERNAME", "root");
define("PASSWORD", "");
$options = array(PDO::ATTR_PERSISTENT => true);
try{
$conn = new PDO(DSN, USERNAME, PASSWORD, $options);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "connection successful";
}catch (PDOException $ex){
echo "A database error occurred ".$ex->getMessage();
}
Related
This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead [duplicate]
(1 answer)
Closed 1 year ago.
I am getting this warning, but the program still runs correctly.
The MySQL code is showing me a message in PHP:
Deprecated: mysql_connect(): The mysql extension is deprecated and
will be removed in the future: use mysqli or PDO instead in
C:\xampp\htdocs\task\media\new\connect.inc.php on line 2
My connect.inc.php page is
<?php
$connect = mysql_connect('localhost','root','');
mysql_select_db('dbname');
?>
What does this mean and how can I eliminate the message?
There are a few solutions to your problem.
The way with MySQLi would be like this:
<?php
$connection = mysqli_connect('localhost', 'username', 'password', 'database');
To run database queries is also simple and nearly identical with the old way:
<?php
// Old way
mysql_query('CREATE TEMPORARY TABLE `table`', $connection);
// New way
mysqli_query($connection, 'CREATE TEMPORARY TABLE `table`');
Turn off all deprecated warnings including them from mysql_*:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
The Exact file and line location which needs to be replaced is "/System/Startup.php > line: 2 " error_reporting(E_All); replace with error_reporting(E_ALL ^ E_DEPRECATED);
You can remove the warning by adding a '#' before the mysql_connect.
#mysql_connect('localhost','root','');
but as the warning is telling you, use mysqli or PDO since the mysql extension will be removed in the future.
Deprecated features in PHP 5.5.x
The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the **MYSQLi or PDO_MySQL extensions.**
Syntax:
<?php
$connect = mysqli_connect('localhost', 'user', 'password', 'dbname');
Also, replace all mysql_* functions into mysqli_* functions
instead of
<?php
$connect = mysql_connect('localhost','root','');
mysql_select_db('dbname');
?>
This warning is displayed because a new extension has appeared.
It suppouse that you still can use the old one but in some cases it´s impossible.
I show you how I do the connection with database. You need just change the values of the variables.
My connection file: connection.php
<?php
$host='IP or Server Name (usually "localhost") ';
$user='Database user';
$password='Database password';
$db='Database name';
//PHP 5.4 o earlier (DEPRECATED)
$con = mysql_connect($host,$user,$password) or exit("Connection Error");
$connection = mysql_select_db($db, $con);
//PHP 5.5 (New method)
$connection = mysqli_connect($host,$user,$password,$db);
?>
The extension changes too when performing a query.
Query File: "example.php"
<?php
//First I call for the connection
require("connection.php");
// ... Here code if you need do something ...
$query = "Here the query you are going to perform";
//QUERY PHP 5.4 o earlier (DEPRECATED)
$result = mysql_query ($query) or exit("The query could not be performed");
//QUERY PHP 5.5 (NEW EXTENSION)
$result = mysqli_query ($query) or exit("The query could not be performed");
?>
This way is using MySQL Improved Extension, but you can use PDO (PHP Data Objects).
First method can be used only with MySQL databases, but PDO can manage different types of databases.
I'm going to put an example but it´s necessary to say that I only use the first one, so please correct me if there is any error.
My PDO connection file: "PDOconnection.php"
<?php
$hostDb='mysql:host= "Here IP or Server Name";dbname="Database name" ';
$user='Database user';
$password='Database password';
$connection = new PDO($hostDb, $user, $password);
?>
Query File (PDO): "example.php"
<?php
$query = "Here the query you are going to perform";
$result=$connection->$query;
?>
To finish just say that of course you can hide the warning but it´s not a good idea because can help you in future save time if an error happens (all of us knows the theory but if you work a lot of hours sometimes... brain is not there ^^ ).
That is because you are using PHP 5.5 or your webserver would have been upgraded to 5.5.0.
The mysql_* functions has been deprecated as of 5.5.0
Source
mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.
Use mysqli_* function or pdo
Read Oracle Converting to MySQLi
Its just a warning that is telling you to start using newer methods of connecting to your db such as pdo objects
http://code.tutsplus.com/tutorials/php-database-access-are-you-doing-it-correctly--net-25338
The manual is here
http://www.php.net/manual/en/book.pdo.php
Warning "deprecated" in general means that you are trying to use function that is outdated. It doeasnt mean thaqt your code wont work, but you should consider refactoring.
In your case functons mysql_ are deprecated. If you want to know more about that here is good explanation already : Why shouldn't I use mysql_* functions in PHP?
PDO class replaces these methods. Example for Mysql or MariaDB :
$BDD_SQL = new PDO('mysql:host='.BDD_SQL_SERVER.';dbname='.BDD_SQL_BASE.';charset=utf8',
BDD_SQL_LOGIN, BDD_SQL_PWD,
array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //launch exception if error
PDO::ATTR_DEFAULT_FETCH_MODE=> PDO::FETCH_ASSOC
));
Source : PDO Class
<?php
$link = mysqli_connect('localhost','root','');
if (!$link) {
die('Could not connect to MySQL: ' . mysqli_error());
}
echo 'Connection OK'; mysqli_close($link);
?>
This will solve your problem.
If you have done your coding then
ini_set("error_reporting", E_ALL & ~E_DEPRECATED);
is good option but if you are in beginning then definitely you should use mysqli.
Well, i just faced such message today when i moved to new hosting! anyway i have tried to change the "mySQL" to "mySQLi" but not working, so i have done this:
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
# Turn off all error reporting
error_reporting(0);
$connect_myconn = "Database Connection";
$hostname_myconn = "localhost";
$database_myconn = "db name";
$username_myconn = "user name";
$password_myconn = "pass";
$myconn = mysql_connect($hostname_myconn, $username_myconn, $password_myconn) or die("<h1 style=margin:0;>A MySQL error has occurred.</h1><p><b>Your Query:</b> " . $connect_myconn . "<br /> <b>Error Number:</b> (" . mysql_errno() . ")</p>" . mysql_error());
mysql_select_db($database_myconn, $myconn);
?>
The trick is to set error reporting off :)
# Turn off all error reporting
error_reporting(0);
For PHP 7+ you can use this code instead:
ini_set('display_errors', 0);
ini_set('log_errors', 1);
Thanks
This is the line that is causing problems.
mysql_connect($dbhost ,$dbuser, $dbpass); mysql_select_db($dbname);
mysql_query("SET NAMES 'utf8'");
mysql_set_charset('utf8');
I just got the code from codecanyon and I don't understand how to fix it. It says that it's deprecated
Please try with example
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Reason:
The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
To Fix:
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.
I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:
error_reporting = E_ALL ^ E_DEPRECATED
But this is not the professional way of coding.
Quick Answer: Change mysql entries to 'mysqli'.
//Conect to server, now we specify the database in the connect request.
$conn = mysqli_connect($dbhost ,$dbuser, $dbpass, $dbname);
$res = mysqli_query($conn, "SET NAMES 'utf-8'");
$bstat = mysqli_set_charset($conn, 'utf-8');
...
mysqli_free_result($res);
...
mysqli_close($conn);
Not-so-quick Answer: mysql extension is obsolete, it has lots of security holes so PHP 5.5+ dropped support for this extension and further versions won't include it.
You should now use mysqli extension, which come in procedural and object-oriented flavors. Or migrate your code to PDO, which is more versatile.
This question already has answers here:
mysqli or PDO - what are the pros and cons? [closed]
(13 answers)
Closed 9 years ago.
So I have this Amazon Web Service database all set up
I'm working off an old tutorial for an application that I'm planning on using it with.
I noticed that mysql_connect was deprecate when I looked it up.
What can I use as an alternative? How can I connect to my amazon database?
<?
mysql_connect("localhost", "username", "password") or die ("Can't connect to database server");
mysql_select_db("videoRecorderDemo") or die ("Can't select database");
mysql_query("SET NAMES 'utf8'");
?>
I get this error:
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'username'#'192.168.1.1' (using password: YES) in /www/zxq.net/r/e/d/red5vptest/htdocs/utility/db.php on line 2
Can't connect to database server
No matter what credentials I use.
It also doesn't help that Amazon's code samples show you connecting in an entirely different way.
The documentation for PHP says
This 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.
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
The error message you are getting is unrelated to the deprecation of mysql_connect. The MySQL username and password you're using ("username" and "password" in your code) are wrong — if you don't know the correct values, check the documentation for the version of MySQL you installed. (You may need to create a user and/or database.)
As several others have mentioned, the supported alternatives to the mysql extension are mysqli and PDO MySQL.
MysqlI (mysql improved) is the successor for mysql.
$Link = new mysqli($Hostname, $Username, $Password, $Database);
$Result = $Link->query('SELECT ...');
$Rows = $Result->fetch_array(MYSQLI_NUM);
One easy alternative to the MySQL extension is MySQLi. Instead of
mysql_connect("host", "username", "password")
... you could connect using e.g.
$db = mysqli_connect("host", "username", "password");
It's probably worth reading this helpful tutorial:
http://phpmaster.com/avoid-the-original-mysql-extension-1/
The manual suggests mysqli as an alternative
http://php.net/manual/en/book.mysqli.php
Should I use php PDO or normal mysql_connect to execute database queries in PHP?
Which one is faster?
One of the big benefits of PDO is that the interface is consistent across multiple databases.
There are some cool functions for prepared statements too, which take some of the hassle out of escaping all your query strings. The portability of PDO is greater than mysql_connect.
So, should I use PDO for those reasons or stick to the traditional mysql_connect?
PDO is a bit slower than the mysql_*
But it has great portability. PDO provides single interface across multiple databases. That means you can use multiple DB without using mysql_query for mysql, mssql_query for MS sql etc. Just use something like $db->query("INSERT INTO...") always. No matter what DB driver you are using.
So, for larger or portable project PDO is preferable. Even zend framework use PDO.
Some quick timings indicate PDO is slightly faster at connecting.
$start = microtime(true);
for($i=0; $i<10000; ++$i) {
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage()."\n";
}
$db = null;
}
$pdotime = microtime(true) - $start;
echo "PDO time: ".$pdotime."\n";
$start = microtime(true);
for($i=0; $i<10000; ++$i) {
$db = mysql_connect($host, $user, $password);
if(!$db) {
echo "Connection failed\n";
}
if(!mysql_select_db($schema, $db)) {
echo "Error: ".mysql_error()."\n";
}
mysql_close($db);
}
$rawtime = microtime(true) - $start;
echo "Raw time: ".$rawtime."\n";
Gives results like
PDO time: 0.77983117103577
Raw time: 0.8918719291687
PDO time: 0.7866849899292
Raw time: 0.8954758644104
PDO time: 0.77420806884766
Raw time: 0.90708494186401
PDO time: 0.77484893798828
Raw time: 0.90069103240967
The speed difference will be negligible anyway; establishing a network connection will likely take a LOT longer than any overhead incurred by PDO, especially if the mysql server is on another host.
You mentioned all the reasons to use PDO yourself. Really, never use the mysql_* functions directly, either use PDO, or use some other library.
With PDO you can uses binded params and that will prevent most sql injection attacks.
You can gain more speed using PDO prepared statements.
standard interface to all db backends
There are a bunch of useful methods (like the fetch* family)
I don't think speed is what people are looking for when they are using PDO -- I don't know if there is a difference, and I honnestly don't care : as long as I'm doing a couple of queries to a database when generating a page, a couple of milliseconds on the PHP side will not change anything.
There are two/three great things with PDO, compared to mysql_* :
More or less constant interface accross databases ; better than using mysql_*, pg_*, oci_*, ...
Object-Oriented API (mysqli_* has an OO-API, but not mysql_*)
Support new features of MySQL >= 4.1 (same as mysqli_*, but not mysql_*, again)
BTW : I'm generally using PDO -- either "by hand", or as it's integrated in / used by Zend Framework and/or Doctrine.
As a sidenote : Even if you are not going to use PDO, note that using mysqli instead of mysql is recommended.
See this page of the PHP manual, about that.
I did some performance testing to compare Mysqli functions to PDO functions using both prepared statements and regular direct queries (tested using select statements on Mysqlnd and MyISAM tables).
I found that PDO queries are just slightly slower than Mysqli, but only slightly. This makes sense since PDO used for this purpose mostly just a wrapper that calls Mysqli functions. The advantage to using PDO is that it makes it a little easier to migrate to a different database because the function names aren't specific to MySQL.
The real performance difference is in whether you use prepared queries. There is a large and significant performance penalty to using prepared queries. Other people who have tested them have found the same results.
The only time prepared queries are faster is if you are preparing a query once and then submitting it thousands of times with different data values. Otherwise, it's always faster to use mysqli::query() or PDO::query(). But it's important to be aware that those functions don't escape data values for you, so you need to remember to use mysqli::real_ escape_ string() or PDO::quote() on data variables.
I would generally recommend using PDO unless there is a specific reason you cannot. If there is no little difference between the two and you have no reason not to use PDO, I believe it would be better to get into the practice of using DB abstraction in your applications than going with mysql_* simply because it is there. I would say let best practice win.
In both cases, you call the same mySQL server from the same Php server ... so you cannot notice a lot of difference.
If you want good performance, think about cache (memcache or simple Php file ...) and make a good data base structure (INDEX ...)
PDO is better than SQl
PDO And His Prepare Statement Provide Best Secure Code against SQL injection
PDO is Object Oriented ;)
PDO is compatible with some Databases Engine As Explained Before
MySQLl_* Is Deprecated and will be removed soon
PDO provide more functionality with less line of codes Example:
Pdo
Connect
Check for "<" And ">" And "#" (This check for global uses)
Prepare
Execute
Close
MySQL_*
Connect
Add Backslash
Xsafe
Check for "<" And ">" And "#" (This check for global uses)
Query
Close
both the same functionality but you compare for codes
PDO is more Humanly Readable :)
So what you think?
If performance isn't a "real problem" for you, you should use PDO. The performance differs by small margins, and PDO has a very nice and portable cross-database interface wich can save you some headaches in case you need to use several database drivers.
The mysql_connect function is deprecated as of PHP 5.5.0 and, as with most deprecated features, will be removed. Therefore, prefer using PDO_MySQL (or another alternative MySQLi ) over mysql_connect.
Source: http://php.net/manual/en/function.mysql-connect.php
Some Advantages of PDO:
Can Access multiple database.
Provided many database driver to connect with different different database.
When you switch from one database to another database, you need not to write all the code to connect with new database, just change the connection string and some query which are required for new database.
It provides prepare statement which is a kind of template of query which compiled only once and can be executed as many times as you want, by just changing the attributes which is called place-holder.
Easy and efficient General Operation like- Insert, update...etc.
PDO database connection code:
<?php
$dbhost = 'localhost';
$dbname = 'clsrepair';
$dbuser = 'root';
$dbpass = '';
try {
$db = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection error: ".$e->getMessage();
}
?>
Normal MySQL database connection code:
<?php
mysql_connect("localhost","root", "");
mysql_select_db ("clsrepair");
?>
or
<?php
$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'clsrepair';
$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
?>
MySQL database connection code easy but PDO has many advantage.
MySQL connection in PHP can be established in two ways:
$mysql = new mysqli('localhost', 'user_name', 'password', 'database_name');
or
$link = mysqli_connect('localhost', 'user_name', 'password');
mysqli_set_charset($link, 'utf8');
mysqli_select_db($link, 'database_name');
Which one is the better and why?
Whichever one you prefer. I would go with the OOP Interface for consistency with the rest of my application, because that's how I use MySqli. Also, in my opinion, the OOP interface way is much cleaner (aesthetically, at least).
The best way to connect to MySQL database in PHP is using PDO driver. PDO offers you parameterized query that lets you avoid SQL injection easily, and other features you may love. It is ready to work with object-oriented programming, which is pretty cool.
PDO also can be used to connect to other kinds of SQL databases, like SQL Server, etc. You have to learn PDO (it's simple) and then you can connect to many kinds of SQL databases.
Connecting using the mysqli extension gives you the ability to use newer MySQL features such as transactional queries and parameterised queries which aren't available using the older mysql extension.
Have a look at http://www.php.net/manual/en/book.mysqli.php
Will you be dealing with more than one database? If so it might be a good idea not to set the database_name in the constructor. Otherwise, no problem. Other than the fact that you set the charset in the second one I don't think there's much of a difference.
if (!function_exists('mysqli_init') && !extension_loaded('mysqli')) {
// error: mysqli extension error
exit('...');
}
$connection = mysqli_init();
#mysqli_real_connect($connection, DBHOST,
DBUSER, DBPASS, DBNAME, DBPORT, NULL, MYSQLI_CLIENT_FOUND_ROWS);
if (mysqli_connect_errno() > 0) {
// error: connection error
echo mysqli_connect_error();
exit();
}
// Force UTF-8.
mysqli_query($connection, 'SET NAMES "utf8"');
This sample according to Drupal6
database.mysqli.inc
Both approaches are valid ways to use the mysqli extension. The first is the object-oriented interface and the second is the procedural interface. They are equivalent and it is simply a matter of preference. See the PHP mysqli documentation.