Changing this from MySQL to MySQLi? [closed]

2020-02-02 03:28发布

问题:

Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 4 years ago.

I've decided to switch to MySQLi, because some people have told me it's more secure.. What I'm really confused about, is the new extensions. I tried just added 'i' after every mysql, but that gave me a crap load of errors. I looked up in the PHP manual why that was happening and there was a whole bunch of other functions.. I honestly can't figure out how to convert. Can you help me out?

include("dbinfo.php");
mysql_connect($c_host,$c_username,$c_password);
@mysql_select_db($c_database) or die(mysql_error());
$mycon = new mysqli($c_host, $c_username, $c_password, $c_database);
$query="SELECT * FROM users WHERE username='" .$_COOKIE['username']. "'";
$result=mysql_query($query) or die(mysql_error());
$num=mysql_numrows($result);
$username=mysql_result($result,$i,"username");

回答1:

Here's what you need to do:

  1. Read the overview so that have an understanding of the differences/advantages.

  2. Consult the old -> new function summary on the PHP site and get your existing code up and running with the mysqli interface.

  3. Take advantage of the improvements (such as using prepared statements) otherwise this is a futile exercise. (By default mysqli really isn't any more secure than mysql.)



回答2:

One of the reasons MySQLi is more "secure" is because it offers a different interface, which is better in many ways. Instead of trying to translate your code directly, learn the new interface and use it. If that's all your code, it wouldn't be easy to rewrite from scratch, and which is more important, look up the equivalents (and alternatives) for everything you're doing in the code that you pasted.

For starters, you should use $mysqli->prepare with parameters instead of interpolating variables like you're doing.

http://www.php.net/manual/en/mysqli.prepare.php