Hi, I have read that using mysqli is much better than normal mysql so I have decided to convert all of the mysql stuff to mysqli stuff in a very new project.

I am new to OOP altogether so I am stuck.

Currently I have a function for checking if something exists in a database:

    function detail_available($table,$detail,$value){
        /* Function for checking dupes. */
        $query     = "SELECT * FROM $table WHERE $detail =  '$value'";
        $result = mysql_query($query);
        $information = mysql_fetch_assoc($result);
        if(!$information){
            return true;
        }else{
            return false;
        }
    } 

and I have tried changing it to this:

	function detail_available($table,$detail,$value){
		/* Function for checking dupes. */
		$available = $mysqli->query("SELECT * FROM $table WHERE $detail =  '$value'");
		$count = $available->num_rows;
		if($count==0){
			return true;
		}else{
			return false;
		}
	}

I am getting errors saying $mysqli is an undefined variable etc etc, is there a way to use the current $mysqli object inside functions that I create? ive searched around on google etc and found nothing. Thanks in advance

BTW the full script that I am editing now is on this forum:

http://phpbuilder.com/board/showthread.php?t=10373497

    [man]mysqli[/man] supports both OOP styles and procedural styles. In my experience, the OOP stuff looks pretty dramatically different than the procedural stuff. It would probably be easier for you to just use the mysqli procedural style instead.

    Something like this:

        function detail_available($table,$detail,$value){
            global $db; // mysqli procedural calls require a reference to the db you opened
            /* Function for checking dupes. */
            $query     = "SELECT * FROM $table WHERE $detail =  '$value'";
            $result = mysqli_query($db, $query); // see that i've used the $db here?
            $information = mysqli_fetch_assoc($result);
            if(!$information){
                return true;
            }else{
                return false;
            }
        } 
    

    The OOP approaches do have certain advantages like the ability to use prepared statements (which takes care of properly escaping values -- something your code does not currently do) and also reduced dependence on global variables which decreases the chance that you'll have a variable name collision.

      Also note that using global variables is a deprecated practice. My suggestion would have been to pass the MySQLi object (assumed to be $db in sneakyimp's code snippet above) to the function as an additional parameter.

        bradgrafelman;10954747 wrote:

        Also note that using global variables is a deprecated practice.

        Holy cow! Does this mean I can expect a notice about deprecated functionality on the superglobals documentation page ? 😉

          Probably not, since a global variable isn't a superglobal variable...

            Well, $GLOBALS is itself a superglobal but contains references to every variable defined in the global scope. Perhaps we'll find the deprecation notice on the [man]global[/man] keyword page?

            I fully agree that use of global variables is usually lazy and is likely to introduce bugs as name collisions occur, but don't you think it's a bit strong to say it's "deprecated" ? To me, that implies the functionality will eventually be removed from PHP.

            Not trying to be pedantic or peevish here. I have learned a lot from brad and am curious about this. I find it sort of difficult to avoid defining things in global scope -- like configuration constants especially.

              My definition of "deprecate" most closely resembles this one: "deprecate - express strong disapproval of; deplore."

              Every reference I have on coding standards/practices usually associates global variables with words/phrases such as "deprecated", "discouraged", "bad practice" (or even simply "bad"), etc. In many of my university classes, if our programs/projects used global variables, we could expect points to be lost (not too many, but more than none).

              Thus, I like to say that it's "deprecated." Does that mean that the PHP developers themselves will "officially" deprecate the use of them? shrug It's possible, but perhaps unlikely. Maybe the use of the 'global' keyword (or $GLOBALS array) will someday generate E_STRICT errors at the very least (as it should, IMHO).

              sneakyimp wrote:

              I find it sort of difficult to avoid defining things in global scope -- like configuration constants especially

              Well that's not fair - constants are not variables, so you're comparing apples to oranges there (IMHO, anyway).

              Perhaps my view on global variables is slightly skewed due to a) the opinion of my teachers/mentors/references, and b) my push towards OOP code (more like a giant shove considering all of the Java code I've been writing lately :p).

                You make sense, brad. I generally agree.

                In the interest of helping the original poster, I'll defend my use of a reference to the global $db var by saying:
                1) the procedural mysqli functions like [man]myqli_query[/man] require that you supply a reference the link reference returned by your original call to [man]mysqli_connect[/man] which made the db connection. Thus, we'll need some reference to $db.
                2) Using a global variable is perhaps a bit easier than changing changing all your function declations and altering every single reference to the functions that make use of the db. If you are willing to risk using a global var, you would only need to define $db as a global var and add "global $db;" to each function that uses the db rather than revisiting each spot where one calls these functions (which could number in the tens or even hundreds or more depending on the scope of the project).

                As for config constants, they are not variables but they do run the same risk as a global name collision. You might get a warning or complaint if you try to redefine a constant I guess, but you'd still have to alter some code were such a collision detected.

                My OOP chops are not super refined, but I have made some pretty extensive use of class constants: MyClass::SOME_CONSTANT. I have heard some rumblings about a registry pattern too.

                Dexter, if you are in the process of redesigning your code, it might be better to make the leap all the way to OOP now. On the other hand, it may be a bit more painful. The suggestion I offered is easier in the short term I think (maybe not!) but I believe OOP might serve you better as a learning exercise and might result in better code.

                  Cheers for all the replies, I have decided against global variables as everywhere ive read they are apparently bad.

                  Ok i have this at the top of the script:

                  $mysqli	= new mysqli($dbhost,$dbuser,$dbpass,$db);
                  

                  I have changed the function to this:

                  	function detail_available($table,$detail,$value,$db){
                  		/* Function for checking dupes. */
                  		if($result = mysqli_query($db,"SELECT * FROM $table WHERE $detail =  '$value'")){
                  			$count = mysqli_num_rows($result);
                  			if($count==0){
                  				return true;
                  			}else{
                  				return false;
                  			}
                  		}else{
                  			//query fail
                  			die('query fail');
                  		}
                  	}
                  

                  the query does not work.

                  I call the function like this:

                  if(detail_available('users','username',$username,$mysqli)){
                  

                  but I believe OOP might serve you better as a learning exercise and might result in better code.

                  I would really like to learn some OOP but it confuses the hell out of me, thats why im trying to play with some objects and classes before I make my own.

                  If anyone would like some more information about what is going on please ask. Again, thanks for the help.

                    DexterMorgan wrote:

                    the query does not work

                    Can you elaborate on this? Does mysqli_query() return false (and, if so, what does mysqli_error() have to say?) or do you get any PHP error messages?

                      Since you are instantiating a MySQLi object, you would need to use it in OOP mode in the function, e.g.:

                      <?php
                      function detail_available($table, $detail, $value, $db)
                      {
                         /* Function for checking dupes. */
                         if ($result = $db->query("SELECT * FROM $table WHERE $detail =  '$value'")) {
                            if ($result->num_rows == 0) {
                               return true;
                            } else {
                               return false;
                            }
                         } else {
                            //query fail
                            die('query fail');
                         }
                      }
                      
                      $mysqli = new mysqli($dbhost,$dbuser,$dbpass,$db);
                      if(detail_available('users','username',$username,$mysqli)){
                         // something
                      }
                      

                        Awesome!

                        Fixed it the last post was me being stupid I forgot that the table was only online and not used with XAMPP, thanks so much for the help, it is all functioning perfectly.

                        Thanks again.

                          @
                          I ended up doing it the procedural way and that worked fine but I have just read your post and the OOP way works now also lol, I am changing it all to OOP now.

                          Thanks for the help everyone!

                            Write a Reply...