Re: [請益] update 資料問題

看板PHP作者 (Swaglicious)時間9年前 (2016/07/17 21:04), 編輯推噓1(107)
留言8則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《Relent (遺憾)》之銘言: : 我在php中做更新紀錄的動作 : 根據print出來的sql語法如下 : update `tableS` set `history`='[{"time":"2016-07-14 : 18:24:22","count":0,"link":"http://aaa.bbb.cc"}]' where account='110101' : 只是我的資料表history欄位裡面的資料,卻變成了這樣 : [{"time":"2016-07-14 : 18:24:22","count":0,"link":"http://aaa.bbb.cc"}, : {"time":"2016-07-14 : 18:24:22","count":0,"link":"http://aaa.bbb.cc"}, : {"time":"2016-07-14 : 18:24:22","count":0,"link":"http://aaa.bbb.cc"}, : {"time":"2016-07-14 : 18:24:22","count":0,"link":"http://aaa.bbb.cc"}] : 多出了3筆同樣的紀錄 : 想請問一下各位大大這種狀況是因為什麼呢 : 程式碼如下, : [code] : $count=0; : $bitStr="1101010101111010"; : while($count<30 && strlen($bitStr)>0){ : $percent=0.1; : $obj=new stdClass(); : $obj->time=$checkDate; : $obj->count=$count*$percent; : $obj->link=$url; : $arr=array(); : array_push($arr,$obj); : $str=json_encode($arr); : $sql="update tableS set history='".$str."' where account='".$bitStr."'"; : echo $sql; : mysql_query($sql); : $count++; : $bitStr=substr($bitStr,0,-1); : } : [/code] 1. 請愛用PDO的parameters binding, 不然遇到SQL injection... 2. 儲存時間最好用timestamp, 不然也期望你是UTC time..否則換server = gg 3. 你如果在php5.5+其實可以直接$str = json_encode([$obj]); 省去 $arr = array(); array_push($arr,$obj); 4. 你的110101010111101 才16個數字, 為什麼要while($count<30)? $bitStrLength = strlen($bitStr); for($i = 0, $i <= strlen($bitStrLength), $i++) 5. 照上面的code來看不應該會output3個一樣的, 但是我如果是你會這樣寫 {code:php} $count = 0; $percent = 0.1; $bitStr = "1101010101111010"; $bitStrLength = strlen($bitStr); for ($i = 0; $i < $bitStrLength; $i++) { // don't really know why you storing objects into json but whatever $obj = new stdClass(); $obj->time = $checkDate; $obj->count = $i * $percent; $obj->link = $url; $str = json_encode([$obj]); $sql = $sql="update tableS set history='".$str."' where account='".$bitStr."'"; echo $sql . "\n"; $bitStr = substr($bitStr, 0, -1); } {code} -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 120.156.64.189 ※ 文章網址: https://www.ptt.cc/bbs/PHP/M.1468760645.A.6EE.html

07/17 21:05, , 1F
喔還有, xdebug是好物。 不用再echo var_dump了
07/17 21:05, 1F

07/19 19:10, , 2F
感謝e大,本來是用pdo的不過寫成了function 呼叫,怕問的
07/19 19:10, 2F

07/19 19:11, , 3F
不清楚,所以把sql語法的部分簡單寫了一下
07/19 19:11, 3F

07/19 19:12, , 4F
<30 是因為其他的狀況會有超過30的
07/19 19:12, 4F

07/19 19:13, , 5F
本來我以為找到解了 結果IE跑久了也是會出現重複的寫入
07/19 19:13, 5F

07/20 10:07, , 6F
就你貼的部分應該是不會重複寫入的, 不然就$sql = ''
07/20 10:07, 6F

07/20 10:08, , 7F
在你loop的最前面. 還有看看pdo->execute()那邊有沒有
07/20 10:08, 7F

07/20 10:08, , 8F
另外的loop
07/20 10:08, 8F
文章代碼(AID): #1NYu95Rk (PHP)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
文章代碼(AID): #1NYu95Rk (PHP)