Jump to content

Multiple questions


Toomas_99

Recommended Posts

1 - Should i use

$row = $select->fetch( PDO::FETCH_OBJ );

when working with oop?

 

Example

public function usernameToId( $username ) 
    {
	    # Create and run query.
	    $query = 'SELECT
					id
			  	  FROM
			  	   	user
			      WHERE
			  	    username = :username';
	    $select = $this->db->prepare( $query );
	    $select->bindParam( ':username', $username, PDO::PARAM_STR );
	    $select->execute();
	    # Retrieve the row( will return an empty array if no records match ).
	    $row = $select->fetch( PDO::FETCH_OBJ );
	    #
	    if ( $row ) 
        {
	        return $row->id;
	    }
	    # No rows matched.
	    return null;
	}

2 . What is corrcect method to see if username exists?

public function usernameExists( $username )
	{
		# Create and run query.
		$query = 'SELECT
					COUNT(id)
			  	  FROM
			  	   	user
			      WHERE
			  	    username = :username';
		$select = $this->db->prepare( $query );
		$select->bindParam( ':username', $username, PDO::PARAM_STR );
		$select->execute();
		#
		if ( $select->fetchColumn() > 0 )
		{
			return true;
		}
		# No rows matched.
		return false;
	}
	
	public function usernameExists( $username )
	{
		# Create and run query.
		$query = 'SELECT
					COUNT(id)
			  	  FROM
			  	   	user
			      WHERE
			  	    username = :username';
		$select = $this->db->prepare( $query );
		$select->bindParam( ':username', $username, PDO::PARAM_STR );
		$select->execute();
		#
		if ( $select->fetchColumn() )
		{
			return true;
		}
		# No rows matched.
		return false;
	}
    
    public function usernameExists( $username )
	{
		# Create and run query.
		$query = 'SELECT
					COUNT(id)
			  	  FROM
			  	   	user
			      WHERE
			  	    username = :username';
		$select = $this->db->prepare( $query );
		$select->bindParam( ':username', $username, PDO::PARAM_STR );
		$select->execute();
		#
		if ( $select->fetchColumn() == 1 )
		{
			return true;
		}
		# No rows matched.
		return false;
	}
Link to comment
Share on other sites

  1. Whether you prefer to get your results as objects or associative arrays is up to you. But you should set the default fetch mode globally in the PDO constructor rather than repeating the setting over and over again for each query.

If you do the check in order to prevent username collisions, then none of the methods is correct. In fact, the whole approach is wrong, because there's a gap between the check and the insertion where another process may take the same name, essentially making the check useless (this is called a time-of-check-to-time-of-use bug). What you need to do is let the database system enforce unique names: Add a UNIQUE constraint to the column, simply insert the name and then check if the constraint has been violated (MySQL has error codes for this).

Link to comment
Share on other sites

  1. Whether you prefer to get your results as objects or associative arrays is up to you. But you should set the default fetch mode globally in the PDO constructor rather than repeating the setting over and over again for each query.

 

Often, the desired format of the results depends on what one is doing with the results.  I probably return objects 60% of the time, associated arrays 30% of the time, and a single column 10% of the time.

 

Currently, I explicitly state the desired format every time.  I believe a benefit of doing so is the intent is smack in front of me.  It seems an advantage of globally setting in the PDO constructor is less typing.  Are there performance advantages or other advantages of setting in the constructor?

Link to comment
Share on other sites

What will this line mean?

if ( $select->fetchColumn() )
{
    return true;
}

I know that this will check if row count is bigger than 0

if ( $select->fetchColumn() > 0 )
{
    return true;
}

And this - If row count is equal to 1

if ( $select->fetchColumn() == 1 )
{
    return true;
}
Link to comment
Share on other sites

Often, the desired format of the results depends on what one is doing with the results.  I probably return objects 60% of the time, associated arrays 30% of the time, and a single column 10% of the time.

I can't think of any reason why one would want some 60/30 split (or whatever) between objects and arrays. Would you mind explaining the logic behind why you'd want an array vs an object in different situations. Fetching a single column is occasionally useful.

 

Are there performance advantages or other advantages of setting in the constructor?

I doubt there's much difference performance wise using though I haven't tested anything. The main reason to use the default is just to keep things consistent across the code base. I've worked on some code bases before where it seemed like have of it fetched as an object and the other half as an array. It was damn annoying switching between styles. Even more annoying was some of the arrays were fetched numerically rather than associatively.

 

As I mentioned above, I cannot think of any reason why you'd want to switch between the two. Pick a style and stick to it. Make it the default to save some typing. If you really really want to, you can always override the default for a specific result set.

 

What will this line mean?

Whatever value is given to an if statement will be cast to a boolean value. The code then branches based on that typecast result. So when there's no explicit condition you just need to look at what values would cast to true and which would cast to false. In the case of an integer value zero is false, everything else is true.
Link to comment
Share on other sites

I can't think of any reason why one would want some 60/30 split (or whatever) between objects and arrays. Would you mind explaining the logic behind why you'd want an array vs an object in different situations. Fetching a single column is occasionally useful.

 

The only reason I said 60/30 is I am going through a transition period where I wish to return objects as I feel they are more readable instead of associated arrays which I did in the past, and I actually feel it should be 91% objects, 4% associated arrays, and 5% columns for me (more or less :) ).

 

And if my new default is an object, there are some times when an array is more applicable such as when I wish to perform some array difference function and don't wish to have to take the extra step to convert the DB result from an object to an array.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.