This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 1 year ago.
Php is not going to promote some MySql functions in upcoming days.
There is some examples about cleaning deprecated functions in PHP manual. But for example; when i replace mysql_query with mysqli_query in code below doesn't work. Also Notepad++ treats them like functions which is defined by myself. All examples are using OOP in PHP manual. I need an example without using object orianted programing.
Can someone tell me that how can i clean my code from deprecated mysql functions?
function db_connect_select()
{
$connection = #mysql_connect(MYSQL_HOSTNAME, USERNAME_SELECT, PASSWORD);
if (!$connection)
{
return false;
}
if (!mysql_select_db(DATABASE))
{
return false;
}
mysql_query("SET NAMES UTF8");
return $connection;
}
function db_result_to_array($result)
{
$res_array = array();
for ($count = 0; $row = mysql_fetch_array($result); $count++)
{
$res_array[$count] = $row;
}
return $res_array;
}
function select_top_tags()
{
$connection = db_connect_select();
$query = 'SELECT * FROM top_tags ORDER BY tag_name ASC';
$result = db_result_to_array(mysql_query($query));
if(mysql_ping($connection))
{
mysql_close($connection);
}
return $result;
}
It will just make no sense.
A mere mechanical replacement will do no good.
You have to understand that it is not old functions themselves, but old ways of using them is discouraged.
So, if you want to keep your current code as is - just keep it.
A red box in the manual is not that scary, and the version in which these functions are actually would raise a deprecated-level error is not out yet.
So, you have a 3-4 years ahead, before you will encounter whatever inconvenience. And even then to turn off deprecated-level errors is a matter of one runtime setting.
But if you want to write the better code - you have to use OOP way with PDO (and I can assure you that OOP is not that scaring. Although it require some knowledge when writing, it is very easy to use a ready made class. The only difference from familiar functions is a little -> thing. Not a big deal)
So, here you go:
function db_connect_select()
{
$dsn = 'mysql:host='.MYSQL_HOSTNAME.';dbname='.DATABASE.';charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
return new PDO($dsn,USERNAME_SELECT, PASSWORD, $opt);
}
function db_result_to_array($query,)
{
// not needed with PDO
}
function select_top_tags()
{
global $pdo;
$query = 'SELECT * FROM top_tags ORDER BY tag_name ASC';
$stm = $pdo->prepare($query);
$stm->execute();
return $stm->fetchAll();
}
usage:
$pdo = db_connect_select(); // somewhere in a bootstrap file
$tags = select_top_tags();
mysqli_* functions are not drop-in replacement for mysql_* functions. They are used in different way and simple replacement will not work. There are many tutorials on the Internet describing how to use mysqli_* functions in PHP, e.g. this one.
I think you should carefully read the manual section on migrating because it specifically talks about the (minor) differences between both extensions.
Some examples:
// no select_db, give db to _connect call
$connection = #mysqli_connect(MYSQL_HOSTNAME,USERNAME_SELECT,PASSWORD,DATABASE);
// need to give the connection parameter to mysqli_query
mysqli_query($connection,"SET NAMES UTF8");
and so on
As others already said, this procedural interface is mostly offered for convenience and to ease the transition. You should at the same time invest some time in mastering the more modern concepts used in the newer db interfaces - I'd strongly suggest you have a look at PDO, presently by far the best database API for PHP.
Related
Am trying to change my project from mysql to mysqli. I have my db connection as:
$link = mysqli_connect($hostname, $username, $password, $database);
if(mysqli_connect_errno()) {
echo "Opps! Connection could not be established: ", mysqli_connect_error();
exit();
}
Then I have a user defined function as:
function get_name($id) {
$query = mysqli_query($link, "select name from staff where id='$id'");
$result = mysqli_fetch_assoc($query);
return $data = $result['name'];
}
I understand that I have to declare $link as global (as shown below) which work fine.
function get_name($id) {
global $link;
$query = mysqli_query($link, "select name from staff where id='$id'");
$result = mysqli_fetch_assoc($query);
return $data = $result['name'];
}
My question here is: Is it a good practice and is it safe?
I wouldn't necessarily call it a good or bad practice to write a function with such a specific purpose, just what fits your needs. If you plan to do this exact task in multiple places throughout your code, a function is useful to make your code easier to read and avoid repeating yourself.
As far as safety goes, you need to sanitize inputs before using them in a query. For the case of an integer $id field, you could simply cast it as an integer $id = (int)$id;. For other data types, you would want to escape it by using $id = mysqli_real_escape_string($link, $id);. Then you'll be safe.
I would also advise that you look into PDO instead of mysqli. I believe it's much more commonly used these days.
Taken literally, this question makes very little sense. User-defined functions almost always are good practice, no matter if you are using them with mysqli or any other API. Yet functions in general have nothing to do with safety.
While speaking of the code provided, it is not safe because of lack of prepared tatements.
So, to make your code proper, you have to create functions to handle mysqli queries with parameters first. And then employ these functions in your own helper functions, to make them look like this:
function get_name($id) {
return dbgetOne("select name from staff where id=?",[$id]);
}
as you can see it will not only make your queries safe, but also shorten your code.
I have used mysql_query() throughout my project; but I've just learned that mysql_ was deprecated as of PHP 5.5, has been removed in PHP 7.
So, I would like to know if I can replace all mysql_ functions with mysqli_ in my project blindly? For example, just replacing mysql_query() with mysqli_query(). Is there any adverse effect?
The short answer is no, the functions are not equivalent.
The good news is there is a converter tool that will help you if you've got a lot of calls/projects to change. This will allow your scripts to work right away.
https://github.com/philip/MySQLConverterTool
It's a forked version of the Oracle original version, and it's kosher.
That said, it's not too difficult to update your code, and you might want to migrate to an object orientated methodology anyway ...
1) The Connection
For all intents and purposes, you need a new connection function that saves the connection as a PHP variable, for example;
$mysqli = new mysqli($host, $username, $password, $database);
Notice I've saved the connection to $mysqli. You can save to $db or whatever you like, but you should use this throughout your code to reference the connection.
Remember to enable error reporting for mysqli before opening the connection;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
2) The Query
Note: You should protect against SQL injection with prepared statements, which are available in MySQLi. Take a look at How can I prevent SQL injection in PHP?, but I'm just going to cover the basics here.
You now have to include the connection as an argument in your query, and other mysqli_ functions. In procedural code it's the first argument, in OO you write it like a class method.
Procedural:
$result = mysqli_query($mysqli, $sql);
OO:
$result = $mysqli->query($sql);
3) Fetch Result
The fetching of the result is similar to the old mysql_ function in procedural;
while ($row = mysqli_fetch_assoc($result))
but as $result is now an object in mysqli, you can use the object function call;
while ($row = $result->fetch_assoc())
4) Close Connection
So as before, you need to include the connection in the close function; as an argument in procedural;
mysqli_close($mysqli);
and as the object that you run the function on in OO;
$mysqli->close();
I would be here forever if I went through them all, but you get the idea. Take a look at the documentation for more information. Don't forget to convert any connection close, result release, or error and row counting functions you have.
The basic rule of thumb is for functions that use the database connection, you need to include it in the function now (either as the first argument in procedural, or the object you use to call the function in OO), or for a result set you can just change the function to mysqli_ or use the result set as the object.
If you cannot convert all calls to the mysqli functions on a old project, you could install and include the library php7-mysql-shim.
It will try to create a transparent replacement for mysql on PHP 7 using mysqli.
Obviously the performance is slower, but it's a solution to get around the problem in a couple of minutes.
You may safely include the library in projects working with PHP 5.6 (it will be ignored).
if (defined('PHP_VERSION_ID') && (PHP_VERSION_ID >= 50600)) { require_once "mysql-shim.php"; }
You can't. some of the functions of mysql and mysqli require different parameters. So you should know which will use the same parameters.
This question already has answers here:
mysqli_query() expects at least 2 parameters, 1 given
(5 answers)
Closed 9 years ago.
Im trying to convert a project of mine from mysql to mysqli but it seems to give me a error
Warning: mysqli_query() expects at least 2 parameters, 1
this is my database connection
$mysqli = new mysqli();
$mysqli->connect('localhost', 'root', '', 'myscript');
this is the query
$sql = mysqli_query("SELECT * FROM settings WHERE id='1'") or die (mysqli_error());
$results = mysqli_fetch_array($sql);
if anyone can tell me how to fix this error i will be grateful. thanks in advance.
You can try performing your query using Object oriented PHP way instead of mixing and matching Object oriented PHP and regular PHP:
$mysqli = new mysqli();
$mysqli->connect('localhost', 'root', '', 'myscript');
if($result = $mysqli->query("SELECT * FROM settings WHERE id='1'")){
//DO STUFF
$result->close();
}else{
printf("Error: %s\n", $mysqli->error);
}
Please, do not convert a project of yours from mysql to mysqli.
Convert it to PDO.
Mysqli is good only for the silly examples from beginner's manual - it will make your life harder as you progress.
So, instead of mysqli just use PDO.
It's almost the same:
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$pdo = new PDO('mysql:dbname=myscript;host=localhost','root','', $opt);
$stm = $pdo->prepare("SELECT * FROM settings WHERE id=?");
$stm->execute(array(1));
$data = $stm->fetch();
Note parameretized query support - the main reason for such a move between drivers - which already used in this code.
Even in such small examples PDO is better. Way better. And with more complex ones mysqli will become totally unusable while PDO would be the same - quite ugly but at least feasible.
Im always using while loop in generating all record in my database, and some of my friend told me that it is better to use foreach in generating record from a database, but i dont know how.
<?php
$query = mysql_query("select * from sampleTABLE");
while($i = mysql_fetch_array){
echo $i['samplefieldName'];
}
?>
My question is, how to display records from my database using foreach? and can some one compare it in the while loop in terms in syntax and generating its result, thank you.
There is no need to use foreach instead of while here as #Zerkms says
while($i = mysql_fetch_array( $query)){
however ou can do this by below code but i am sure its not good approach
$result_list = array();
while($row = mysql_fetch_array($query)) {
result_list[] = $row;
}
foreach($result_list as $item) {
//you can now echo $item ; or whatever you want
}
Note
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. So use either PDO or MySQLi
Good read
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
PDO Tutorial for MySQL Developers
Pdo Tutorial For Beginners
Firstly, the mysql_xxx() functions are deprecated. They are not recommended for use. There are two alternatives in PHP that are recommended instead -- mysqli() and PDO.
The older mysql_xxx() functions do not allow you to use foreach to loop through a recordset.
However, both the newer alternative APIs do allow this, as they implement the Iterator interface.
So yes, it is possible to use foreach to loop through a recordset in PHP, but not with the old mysql_xxx() functions.
You could write code like this:
$conn = new mysqli(....);
foreach ( $conn->query('SELECT ....') as $row ) {
print_r($row);
}
or like this:
$db = new PDO('mysql:....', $user, $pass);
foreach ($db->query('SELECT ....') as $row) {
print_r($row);
}
Having said that, please note that it's only been possible to do this with mysqli since PHP v5.4, so you'll need to be up-to-date with your PHP version for that. PDO on the other hand has supported this feature for ages.
They can, of course, both also use a while loop as well, and this is where your friend isn't quite right, because really there isn't any difference between while and foreach here. Switching from while to foreach won't make any difference to the performance of your code. They do the same thing under the hood. foreach in this case is really just "syntactic sugar".
I would strongly recommend switching to one of these newer APIs, even if you don't plan to use foreach to do your looping, because as I say, the old mysql functions are deprecated, which means that they are likely to be removed entirely from future PHP versions. So if you want your code to keep running into the future, you should switch now.
It's not possible to iterate over a result set using foreach.
foreach only works for cases when you already have the data fetched.
So your friend was just wrong and his advice doesn't make any sense.
#zerkms
I also thought like that.. But following works...
My 'tbl_login' table structure also attached as a
<?php
include '../common/dbConnection.php';
class foreachtest{
function foreachtesting(){
$sql="SELECT * FROM tbl_login";
$query_result=$GLOBALS['con']->query($sql);
return $query_result;
}
}
$myobject = new foreachtest();
$result=$myobject->foreachtesting();
foreach ($result as $a){
echo $a['username'];
}
?>
tbl_login MYSQL table screenshot
Alright, I'm pretty confident I did this only a few days ago, although I may be going crazy. I am attempting to loop through an SQL result array for example..
$query = mysql_query("SELECT * FROM `my_table`");
$result = mysql_fetch_assoc($query);
Now $result should return multiple rows.. and it does if I loop through it using a while loop. Unfortunately, Im trying to access this data with a foreach loop, and for some reason it will not work. Its only giving me the first row and print_r($result) only gives me the first row as well.
foreach($result as $name => $value)
echo "$name = $value\n";
Any suggestions would be appreciated!
** EDIT:
I love all of the smart answers.. I know the website for the php manual and I know what mysql_fetch_assoc() returns. Here is my solution:
function returnSQLArray() {
$returnArray = array();
$row = 0;
$query = mysql_query("some sql");
while($result = mysql_fetch_assoc($query)) {
$returnArray[$row] = $result;
$row++;
}
return $returnArray;
}
$result = mysql_fetch_assoc($query); returns a single row... you need to loop fetching each row. You're looping through that one row to extract each column.
What Vladson is sarcastically pointing out is nonetheless very true. My forays into PHP programming (many years' worth) have been ever-sprinkled with a great many readups on the php.net site. I'd call it the best online programming documentation in existence, far beating any other language I've used in 20 years.. mostly because of the amazing calibre of the community contributions.
Also, I'd highly recommend abstracting what you're talking about into a db helper class. Reference perhaps the PHPBB code for an example. PHPBB code may be less OO than is ideal, but it's still a good reference point for architecture. And, don't just do this because you may switch out your data layer or change the version, but because it makes it trivial to introduce common error reporting, query logging, data caching, and many other such useful features. This also makes it easier to juggle more than one connection.
Example might be so that you can expose an interface more like: (excuse the very ADODB nature here, but it's still a nice way to think of MySQL, too)
include "db.inc.php";
$SQL = "SELECT * FROM user WHERE id=123";
$oDB = new Database("localhost", "database", "user", "password");
$oRS = $oDB->NewRecordSet($SQL);
while( $data = $oRS->Read() ) {
// do stuff
}
In this manner, the pages have to worry less about the tedium of accessing the data, and can just think more about how to filter the data and what to do with it.
while ($result = mysql_fetch_assoc($query))
{
// do stuff
}
There is a thing called Manual http://www.php.net/manual/en/function.mysql-fetch-assoc.php examples are also there (a lot of them)