12

So as MYSQL is deprecated and eveyone keeps telling me to update, I thought it was about time I did.

But as I'm not used to mysqli_*, it seems alien to me. And it's not a simple edit when I have a whole site coded in Mysql.

So I'm wondering: How would I transform the below code into Mysqli? Just to give me and anyone else a good starting point when dealing with querying the database.

$sql_follows="SELECT * FROM friends WHERE user1_id=".$_SESSION['id']." AND status=2 OR user2_id=".$_SESSION['id']." AND status=2";
$query_follows=mysql_query($sql_follows) or die("Error finding friendships");
if($query_follows>0){
}

EDIT: On reading up and editing my whole site the above code converted to MYSQLI_ would go something like this..

 $Your_SQL_query_variable= mysqli_query($connectionvariable,"SELECT * FROM friends WHERE user1_id=".$_SESSION['id']." AND status=2 OR user2_id=".$_SESSION['id']." AND status=2")) {
        printf("Error: %s\n", $mysqli->error);
    }
Scott C Wilson
  • 19,102
  • 10
  • 61
  • 83
dave
  • 1,009
  • 5
  • 15
  • 26
  • This post has a nice example: http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php – PeeHaa Aug 18 '12 at 16:29
  • 2
    As a sidenote, now that you're switching to MySQLi you should use prepared statements instead of string concatenation for adding specific values to your SQL. Else you might get a visit from [little Bobby Tables](http://bobby-tables.com). – Sebastian Paaske Tørholm Aug 18 '12 at 16:38
  • 1
    Ya just can beat using models; think of how easy it would be if you had a methods like `$model->get_friendships($_SESSION['id']);`, time for some refactoring.... – Lawrence Cherone Aug 18 '12 at 16:39
  • How does your method work @LawrenceCherone – dave Aug 18 '12 at 16:42

2 Answers2

26

You can download a converter tool from here:

https://github.com/philip/MySQLConverterTool

The code it generates is pretty gross, mainly because of the way it implements the default database link argument with a $GLOBAL variable. (This also makes it easy to recognize when someone is using code that's gone through the converter.)

There's also a MySQL Shim Library located here:

https://github.com/dshafik/php7-mysql-shim

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Fantastic. I've just completed converting before seeing this..But this will help in the future and for anyone else also converting. – dave Aug 19 '12 at 12:56
  • @Barmar. I am searching everywhere for the mirror as the link on the page above is dead. Do you know where I can find it now?Thanks. – BernardA Dec 09 '13 at 15:26
  • @BernardA Google found a GitHub repository. – Barmar Dec 09 '13 at 15:43
2

The best place to transform is to look at the php reference library. Very easy to use and will tell you everything you need to know:

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

Conrad Lotz
  • 8,200
  • 3
  • 23
  • 27