0

I am newbie and need help to resolve my issue.

extract row values without loop.

Table:

 ----------------
  YEAR  | SALES
 ----------------
 2011  |     45
 2012  |     34
 2013  |     23
 2014  |     10
 2015  |     48
 ----------------

PHP code:

$sql = "SELECT YEAR FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "YEAR: " . $row["YEAR"]. "<br>";
    }
} else {
    echo "0 results";
}

looking for solution to output the year value without loop , something similar below while loop prints all row values , but would like to extract individual year value from query and assign it to a variable

$year1 = $row["YEAR"]
$year2 = $row["YEAR"]
$year3 = $row["YEAR"]
8
  • What about group_concat to concatinate all years in one item? Commented Jul 9, 2016 at 8:14
  • What is the issue with using a loop? Have you thought about what you will do next year? Edit your code for having a year added? That is not really the right way to do it... Commented Jul 9, 2016 at 8:15
  • 1
    You can use $result->fetch_all() to get a 2-dimensional array, then use $year1 = $rows[0]['YEAR'] Commented Jul 9, 2016 at 8:18
  • tangled issue,. $sql = "SELECT DISTINcT YEAR FROM MyGuests WHERE YEAR = 2014";$result = $conn->query($sql);$year = $result->fetch_raw(),var_dump($year).Maybe you say so ? Commented Jul 9, 2016 at 8:23
  • $result->fetch_all() is not working Commented Jul 9, 2016 at 8:25

1 Answer 1

1

with your current code

       $i=1;
       while($row = $result->fetch_assoc()) {
           ${'year'.$i}= $row["YEAR"];
           $i++;
           //echo "YEAR: " . $row["YEAR"]. "<br>";
          }

now you can access $year1; $year2 and so on

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

1 Comment

i am glad it helped. and yes others are correct; using array would be more manageable.. but that was not the question i guess..:)

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.