Jump to content

[SOLVED] Retrieving values from Associative arrays?


idire

Recommended Posts

I can do this in normal php, but with oo php the point is to make all the database transaction happen inside the class right?

 

I have this:

 

<?php
class dbHandle
{
const HOST = 'localhost'; // Server
const USERNAME = 'root'; // Username
const PASSWORD = ''; // Password
const DATABASE = 'db1'; // Database Name

function connect()	// Database Connection
{
	$this->conn = mysql_connect(self::HOST, self::USERNAME, self::PASSWORD) or die("DB Connection Failure");
	mysql_select_db(self::DATABASE);
}

function query($query)	// Return generic query result
{
	$result = mysql_query($query, $this->conn) or die("Query Failure: <br/> $query <br/>" . mysql_error());
	return $result;
}

function fetchArray($query) // Return query result as an associative array
{
	$result = $this->query($query);
	$result = mysql_fetch_assoc($result);
                return $result;		

	//while($r = mysql_fetch_array($result)) {
		//return $result;
	//}
}

 

and I have a simple table I made to test with columns username, and password

 

Question 1: How should I execute select queries? I can do it by doing:

 

$result = $con->query('SELECT * FROM `user`');

 

but should it be done a better way?

I mean by sending the type of query and the variables? (instead of the query itself)

Having a function for each type of query? select/update/delete

 

Question 2: If I want to retrieve all the values from a query in normal php I would do:

 

<?php
$result = mysql_query('SELECT * FROM `user`');
while($r = mysql_fetch_array($result)) {	
     $temp1 = $r["username"];
     $temp2 = $r["password"];
     //do something with the data then repeat
}

 

how would I do that same with objects? (again by moving all the actual database code to the function and not needing $r["rowname"] outside the function

 

 

Link to comment
Share on other sites

This function is designed wrong.

 

   function fetchArray($query) // Return query result as an associative array
   {
      $result = $this->query($query);
      //$result = mysql_fetch_assoc($result);
      
      while($r = mysql_fetch_assoc($result)) {
         $result[] = $r;
      }
      return $result;
   }

 

the fetch_Array will return both assoc and non-assoc, the above will not just return the assoc, saves on array space.

 

Onto QUestion 1:

 

You would generally only use the query function to execute the UPDATE, INSERT and DELETE queries outside of the class unless you are looking to do something different. I would do it like this instead:

 

$result = $con->fetchArray("Select * from `user`");

 

That way it returns the array, if you want it to and you do not have to do the extra code.

 

The point of the class is to reduce repeat code by having functions do the work for you instead of having to code it each time you need it. Anyhow I hope that helps you with your questions.

Link to comment
Share on other sites

Not really sure what you mean by my code giving me two types of array, I couldnt make this work

 

I tried this code:

 

	
<?php
function fetchArray($query) // Return query result as an associative array
    {
    	$result = $this->query($query);
      	//$result = mysql_fetch_assoc($result);
     
      	while($r = mysql_fetch_assoc($result)) {
         	$result[] = $r;
      	}
      	return $result;
   	}

 

<?php
$conn = new dbHandle();
$conn->connect();

$result = $conn->fetchArray('SELECT * FROM `user`');

 

=

 

Warning: Cannot use a scalar value as an array in class_lib.php on line 27

 

Warning: Cannot use a scalar value as an array in class_lib.php on line 27

 

 

Link to comment
Share on other sites

Figured the problem was the naming of variables so did this:

 

  
<?php  
    function fetchArray($query) // Return query result as an associative array
    {
    	$result = $this->query($query);
      	//$result = mysql_fetch_assoc($result);
     
      	while($r = mysql_fetch_assoc($result)) {
         	$output[] = $r;
      	}
      	return $output;
   	}

 

<?php
$andrew = new dbHandle();
$andrew->connect();

$result = $andrew->fetchArray('SELECT * FROM `user`');
echo $result[0];

 

this shows nothing on the screen, but removes the errors

 

 

EDIT again:

 

<?php
print_r($result);

gives:

Array ( [0] => Array ( [username] => user1 [password] => password1 ) [1] => Array ( [username] => user2 [password] => pass2 ) ) 

 

so now I can access the data by using a while loop? not sure how to display that either.

 

 

Link to comment
Share on other sites

I can get result on the page to print_r as:

 

Array ( [0] => Array ( [username] => user1 [password] => password1 ) [1] => Array ( [username] => user2 [password] => pass2 ) )

 

So now I need a for/while loop echoing:

 

echo $result[0][username];

echo $result[0][password];

 

those work, i just cant recall offhand how to cycle though an array and stop when it finishes

 

thanks for the help by the way

Link to comment
Share on other sites

I can get result on the page to print_r as:

 

Array ( [0] => Array ( [username] => user1 [password] => password1 ) [1] => Array ( [username] => user2 [password] => pass2 ) )

 

So now I need a for/while loop echoing:

 

echo $result[0][username];

echo $result[0][password];

 

those work, i just cant recall offhand how to cycle though an array and stop when it finishes

 

thanks for the help by the way

 

You can do something along these lines:

 

for($i = 0; $i < count($result); i++)
{
   echo $result[$i]['username'];
   echo $result[$i]['password'];
}

Link to comment
Share on other sites

using a for loop with count is inefficient.  At the beginning of each loop, the script has to recount the array, so if your query ever returns a large amount of data (say 100 rows or so), you might notice some lag.  I prefer using foreach loop:

foreach($result as $row)
{
   echo $row['username'];
   echo $row['password'];
}

 

Same results and it should be faster.

Link to comment
Share on other sites

Thanks.

 

I have a php script on a different site that needs to cycle through 400+ rows, then perform data on each and its getting very slow.

 

So is there an easy way to obtimise this type of loop:

 

while($r = mysql_fetch_array($result))

{

}

 

Thanks :)

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.