我正在尝试使用此脚本使用随机生成的数据字段更新我的表
for($i = 0; $i < 10 ; $i++){
$date = rand(1,30).'/'.rand(1,12).'/'.'15';
$dbh = new PDO('mysql:host=localhost;dbname=qp', 'root', '123456');
$sth2 = $dbh->prepare("update r_data set the_date = '$date' where transaction_type = 'send'");
echo $date.'<br/>';
$sth2->execute();
}
但是该字段仅使用一个随机字符串进行更新,即18/5/15
但变量$date
已根据需要生成随机日期。
为什么日期字段没有使用随机数据更新?
您每次都更新相同的行。循环完成后,您只会看到数据库中的最后一个"随机"值,因为所有前面的值都将被替换。
如果要查看不同行的不同日期,则必须限定要更新的行在循环的每次迭代中都不同。
或者,让MySQL为您插入随机日期:
update r_data set
the_date = DATE '2015-01-01' + INTERVAL FLOOR(RAND() * 365) DAY
where transaction_type = 'send'
这将为每个选定的行插入不同的随机日期值;无需循环。