简体   繁体   中英

Why are my values being saved in ascending order in the database?

I've just noticed that my rand values are being saved in ascending order (lower to higher), but I'm not telling it to save it in ascending order. However when I echo the rand, it shows the value in normal way.

Source code:

<?php
try {
  $db = new PDO('sqlite:randvalue.sqlite');
  $db->exec("CREATE TABLE company (revenue_value INTEGER PRIMARY KEY, month VARCHAR)");

  $i=1;
  while($i <= 12) {
    $randNum =  rand(1,100);
    $finalval = $randNum;
    $stmt = $db->prepare('INSERT INTO company (revenue_value) VALUES (?)');
    $stmt->execute(array("$finalval"));
    echo "$finalval";
    echo "<br>";
    $i++;
  };

  print "<table border=1>";
  print "<tr><td>value</td>";
  $result = $db->query('SELECT * FROM company');

  foreach($result as $row) {
    print "<tr><td>".$row['revenue_value']."</td>";
  }
  print "</table>";

  $db = NULL;

} catch(PDOException $e) {
  print 'Exception : '.$e->getMessage();
}
?>

Result:

在此处输入图片说明

How do I make it not to save the value in table in non-ascending order just like in echo where the values are not in ascending order?

The database will attempt to store the rows in the most efficient way it can for fast lookup. This means storing them in the order defined by the primary key of the table, if one exists, and in this case, the revenue_value column is the primary key. There's no guarantee that the order in which records are inserted is the order in which they will come back when you do a SELECT .

If you want to pull the back in the records same order, you'll need a separate column to store the order in which they are inserted. Typically, you'd use a AUTO_INCREMENT column that's also the primary key of the table. Add a column like this and you'll be able to pull them back in the order in which they are inserted by using an ORDER BY clause. However, as I said, the database will usually attempt to store the rows efficiently, it order them by the primary key column anyway, so typically you wouldn't need the ORDER BY , but it's still a good idea to include one in any query where the order of the results is important.

thanks to @Rizier manage to find the problem

just remove the primary key

$db->exec("CREATE TABLE company (revenue_value INTEGER PRIMARY KEY, month VARCHAR)");

to

  $db->exec("CREATE TABLE company (revenue_value INTEGER, month VARCHAR)");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM