-1

I wish to update the values in column stemp but all must be different and random between 30 and 70.

for($i=0;$i<=30;$i++)
{
    $temp= mt_rand(30,70);
    mysqli_query($con,"UPDATE sensor SET stemp= $temp");
}
Vamsi Krishna B
  • 11,039
  • 14
  • 64
  • 93
bhishaj
  • 39
  • 1
  • 10

2 Answers2

2

You can also use MySQL's RAND() function:

mysqli_query($con, "UPDATE sensor SET stemp=ROUND(RAND() * 40) + 30");

Putting this into a loop does not make sense either since you don't seem to have any kind of WHERE condition in your update statement so all records will be updated every time.

martynasma
  • 8,444
  • 2
  • 26
  • 43
1

I think you want to change your logic a bit:

First of create an array from 30 - 70 with range(). Then shuffle() the array and take an array_slice() from it. With this you have 30 elements, which you can loop through an update your db entries. Like this:

<?php

    $arr = range(30, 70);
    shuffle($arr);
    $update = array_slice($arr, 0, 30);

    foreach($update as $v)
        mysqli_query($con, "UPDATE sensor SET stemp = $v");

?>
Rizier123
  • 57,440
  • 16
  • 89
  • 140