계산식 문의
본문
완전 초보라 아주 기초적인 지식으로 작업중이라 도움 부탁드립니다.
wr_stotal / wr_price / wr_qty 이 1~10까지 있습니다.
그러니까
wr_stotal1 ~ wr_stotal10
wr_price1 ~ wr_price10
wr_qty1 ~ wr_qty10
이렇게 있습니다.
제가 아는 게 아래의 소스를 10번까지 쭉 나열하는것 밖에 몰라서
if문 for문 이런걸 어떻게 쓰는지를 잘몰라서
물론 쭉 나열해도 크게 문제는 없지만 소스를 좀 줄일수 있을까 해서 문의 드립니다.
부탁드립니다.
//wr_stotal1
$wr_stotal1 = $wr_price1 * $wr_qty1 ;
$sql = "update $write_table set wr_stotal1='$wr_stotal1' where wr_id='$wr_id'";
sql_query($sql);
답변 4
$arr = array();
for($i=1; $i<=10; $i++){
$wr_price = ${"wr_price".$i};
$wr_qty = ${"wr_qty".$i};
$wr_stotal = $wr_price * $wr_qty;
$arr[] = "wr_stotal".$i." = ".$wr_stotal;
}
$str = implode(", ", $arr);
$sql = "update ".$write_table." set ".$str." where wr_id=".$wr_id;
sql_query($sql);
이렇게 하면 될듯요 오타있을 수 있으니 확인하시고요..
일단 조금 나온 코드는 다음과 같습니다.
$wr_stotal1 = $wr_price1 * $wr_qty1 ;
$wr_stotal2 = $wr_price2 * $wr_qty2 ;
$wr_stotal3 = $wr_price3 * $wr_qty3 ;
$wr_stotal4 = $wr_price4 * $wr_qty4 ;
$wr_stotal5 = $wr_price5 * $wr_qty5 ;
$wr_stotal6 = $wr_price6 * $wr_qty6 ;
$wr_stotal7 = $wr_price7 * $wr_qty7 ;
$wr_stotal8 = $wr_price8 * $wr_qty8 ;
$wr_stotal9 = $wr_price9 * $wr_qty9 ;
$wr_stotal10 = $wr_price10 * $wr_qty10 ;
$sql = "
update $write_table
set wr_stotal1 = '$wr_stotal1',
wr_stotal2 = '$wr_stotal2',
wr_stotal3 = '$wr_stotal3',
wr_stotal4 = '$wr_stotal4',
wr_stotal5 = '$wr_stotal5',
wr_stotal6 = '$wr_stotal6',
wr_stotal7 = '$wr_stotal7',
wr_stotal8 = '$wr_stotal8',
wr_stotal9 = '$wr_stotal9',
wr_stotal10 = '$wr_stotal10'
where wr_id = '$wr_id'
";
sql_query($sql);
소스코드를 줄이는 것도 중요할 수 있지만,
가독성 및 퍼포먼스도 중요하다고 보았을 때,
DB 쿼리 실행을 한번으로 하는 게 가장 중요합니다. (소스코드 줄이는 것은 부차적일 수 있습니다.)
$wr_stotal1 ~ $wr_stotal10 을 구하는 부분을 for 문으로 할 수는 있으나,
$wr_price1, $wr_qtr1 이 배열로 되어있지 않아 가변 변수를 사용해야 하는데..
개인적으로 가변 변수 사용은 잘 권장하지 않는 편입니다. http://chongmoa.com/php/13412
$wr_price1 ~ 10 을 배열로 변경이 가능하다면, https://www.w3schools.com/php/php_arrays.asp
그 때 $wr_stotal1 ~ $wr_stotal10 은 for 문을 사용할 수 있습니다. https://www.w3schools.com/php/php_looping_for.asp
천천히 익힌 후 활용하시면 될 듯 합니다.
!-->그러니까 뭘 하시려는 거예요?
아~
wr_price1 X wr_qty1 = wr_stotal1
이렇게 수식을 넣으려고 하는건데...
계속 반복된 식을 넣어야 해서
줄여서 쓸수 있는 방법이 없을까 해서 문의 드렸습니다.