1

I'd like to visualize last 144 temperature data from MySQL database on my website. Now I have the following code:

<?php
$servername = "localhost";
$username = "_accounts";
$password = "---";
$dbname = "_accounts";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT `t` FROM `WbabZwvgf` ORDER BY `id` DESC LIMIT 144";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    $t = $row["t"];
  }
} else {
  echo "0 results";
}
$conn->close(); 

Now if I echo $t after i have declared in "while" like this:

while($row = $result->fetch_assoc()) {
    $t = $row["t"];
    echo $t." ";
  }

seems everything OK, but I can't save each values as php variables like $t1=t[0], $t2=t[1], $t3=t[2]...etc, even during the "while". Could you help me how to save the selected data into PHP variables?

2
  • 1
    Save the values in an array instead of a string Commented Jan 3, 2021 at 12:29
  • mysqli_result::fetch_all Commented Jan 4, 2021 at 3:40

2 Answers 2

0

Try

$t = array();
while($row = $result->fetch_assoc()) {
    $t[] = $row["t"];
    
  }
var_dump($t);
Sign up to request clarification or add additional context in comments.

Comments

0

You should use an array. But the correct answer for your question is:

$i = 1;
while($row = $result->fetch_assoc()) {
    ${'t'.($i++)} = $row['t'];
}
echo $t1;
echo $t2;

--

Thanks for the minus. But read his question correctly. He asks for $t1, $t2 and so on. And now consider which answer is the correct one. The one with the array certainly not.

1 Comment

The "correct" answer is not necessarily the one that simply gives what is asked for. The question might be founded on an incorrect assumption or taking the wrong approach (as this one is), in which case a correct answer is one that corrects the error in the question itself.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.