0

I am using the following to put all the data from a database into an array.

  $query = "SELECT * FROM images ORDER BY id ASC";
  $result = mysqli_query($link, $query); 
  $row = $result->fetch_array();

I usually use a while loop to loop though the array and do something with the data. In this case, I need to manually select certain rows from the database, but without using multiple query's. How can I select for example the third result that is in the array with the row name "image"?

I'm sure I've done this before, but can't remember how. I tried using code like $row['image'][3] but that just gets the third letter.

Thanks.

6
  • 3
    Add a filter to your query. Commented Feb 9, 2015 at 13:30
  • @MatteoTassinari Didn't notice that before! Thanks Commented Feb 9, 2015 at 13:34
  • @X.L.Ant Care to explain? Commented Feb 9, 2015 at 13:34
  • Thanks for the down votes without explanation. Great way to help new members! Commented Feb 9, 2015 at 13:36
  • If you know which image you want to access to, why not add a WHERE ... clause to your query (or JOIN if you need to link them to other data) to select only the relevant images ? Commented Feb 9, 2015 at 13:36

4 Answers 4

1

You can cast all of the results to an array and then use the index numbers as the rows.

$query = "SELECT * FROM images ORDER BY id ASC";
$result = mysqli_query($link, $query) or die("Error!.." . mysqli_error($link));
$rows = array();
$rows[0] = ''; // For sake of readability and usability we fill the first index with nothing, this way the first row will be saved in the [1] index.
while($row = $result->fetch_array()){
    $rows[] = $row;
}

Then afterwards you can use the results of row 5 by using $rows[5]['columnname'];

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks this is the correct answer. Don't understand why all the down votes however
I guess the question itself could have been formulated a bit better. But I got what you wanted to do so hence I could give an answer!
Thanks. I struggle with things like that sometimes. I find it hard to explain myself. I did spend at least 10 minutes re-writing it.
A good thing to do when asking a question as to why the code isn't functioning properly or it's incomplete. Is to add in your expected results. So people know what your are getting at. Clears up some possible mishaps in wording your problem.
0
$query = "SELECT * FROM images ORDER BY id ASC" or die("Error!.." .mysqli_error($link)); 
  $result = mysqli_query($link, $query); 
  $row = $result->fetch_array();
  $thirdcol= $row['2'];
echo $thirdcol;

Here you go.

Or you can use $row['ColName']; ex: $row['StackoverFlow'];

Arrays Start with 0! so 0 is one for us.

1 Comment

Not quite. I know how to select columns, I need to be able to select rows and columns together.
0
$found = false;

while (!$found && $index < $row.length) {
   if ($row[$index] === IMAGE_NAME) {
     ++$count;
   } else if ($row[$index] === IMAGE_NAME && $count < THIRD_MATCH ) {
     $found = true;
     $match = $row[$index];
   }
   ++$index;
}

3 Comments

You should add an explanation as too why this is the solution
I thought the code is enought explanatory. Loop thought the array till you find a match and keep track of the matches found with a counter variable. Once you reach the desire match set found flag to true so you don't keep looping and that's itThere is some variables initialization missing as $index, $match. Just make sure to move it to a good named function and initialize everything on the top
It may be self-explanatory to some people, but it's always better to post code with an explanation for those who may not find it as such.
0

Try this: http://www.weberdev.com/get_example.php3?ExampleID=1628

<?php
/*==================================
Author : Lord Nightslave
[email protected]
Load a query result into two dimensional array.
You can later refer the result in an array form with
the original field name.
i.e print $myresultarray[$i]["My Table Field Name"]
====================================*/
?>
<?php
/* You can put this in other file and just include it */
function OpenDb($hostname,$uid,$pwd,$dbname){
$link = @mysql_pconnect($hostname,$uid,$pwd);
if($link && mysql_select_db($dbname)){
return($link);
}
else{
return(FALSE);
}
} 
?> 
<?php
function QueryIntoArray($query){
        settype($retval,"array");

$result= mysql_query($query);
        if(!$result){
print "Query Failed";
        }        
        for($i=0;$i<mysql_numrows($result);$i++){
                for($j=0;$j<mysql_num_fields($result);$j++){
                        $retval[$i][mysql_field_name($result,$j)] = mysql_result
($result,$i,mysql_field_name($result,$j));
                }//end inner loop
        }//end outer loop
return $retval;
}//end function
?>
<!--An Example How To Use The functions 
To try it simple change the appropriate variable to your own database & tables
-->
<HTML>
<HEAD>
<TITLE>PHP Array Test</TITLE>
</HEAD>
<BODY BGCOLOR=WHITE>
<?php
OpenDb("myhost","myuid","mypwd","mydatabase") or die("Failed Opening Database");
settype($myresult,"array");

$query = "SELECT * FROM mytable";
$myresult = QueryIntoArray($query);
for($i=0;$i<count($myresult);$i++){
print $myresult[$i]["MyField1"];
print $myresult[$i]["MyField2"];
}
?>
</BODY>
</HTML>

1 Comment

I'm not sure why all of this extra code is really necessary. Thanks anyway though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.