2010-12-05 92 views
0

我有這樣的:PHP:使清潔和更短的代碼

<?php 
if($_GET['wE'] && is_numeric($_GET['wE'])){ 
$we = mysql_real_escape_string($_GET['wE']); 
$query_find_we = "SELECT id FROM users_wall WHERE id = '$we' AND uID = '$showU[id]'"; 
$query_find_we = mysql_query($query_find_we)or die(mysql_error()); 
$grab_wall_comment = (mysql_num_rows($query_find_we) == 1) ? "window.location.hash = '#comment$we';" : "alert('Vägginlägg kunde ej hittas.');"; 
?> 
<script> 
$(function() { 
<?php echo $grab_wall_comment; ?> 
}); 
</script> 
<?php 
}elseif($_GET['sE'] && is_numeric($_GET['sE'])){ 
$se = mysql_real_escape_string($_GET['sE']); 
$query_find_se = "SELECT id FROM users_statuslog WHERE id = '$se' AND uID = '$showU[id]'"; 
$query_find_se = mysql_query($query_find_se)or die(mysql_error()); 
$grab_status_comment = (mysql_num_rows($query_find_se) == 1) ? "window.location.hash = '#comment$se';" : "alert('Status kunde ej hittas.');"; 
?> 
<script> 
$(function() { 
<?php echo $grab_status_comment; ?> 
}); 
</script> 
<?php 
    } 
?> 

檢查是否有任何$ _GET [ '我們']或$ _GET [ '本身'],如果它的存在。並運行<script>

有沒有辦法讓這個縮短?我嘗試着自己製作一個布爾值,但也許你可以將它縮短一些?任何想法,我想使清潔編碼在未來..

+0

把它包裝在一個函數中.. – Radu 2010-12-05 16:00:19

+0

請回答並提供你如何通過將它包裝在一個函數中的例子。 – Karem 2010-12-05 16:03:22

回答

1

你不知道嗎?

顯然有兩個相同的代碼部分。
您必須將此代碼的可變部分變成PHP變量。就這樣。
當然,應該使用一些db API函數。

<? 
if (!empty($_GET['wE'])) { 
    $id = $_GET['wE'] 
    $table = "users_wall"; 
    $alert = "Vagginlagg kunde ej hittas."; 
} elseif (!empty($_GET['sE'])) { 
    $id = $_GET['sE']; 
    $table = "users_statuslog"; 
    $alert = "Status kunde ej hittas."; 
} 
$query = "SELECT count(id) FROM `$table` HERE id = %d AND uID = %d"; 
$count = db::getOne($query,$id,$showU['id']); 

//Separate your main PHP logic from presentation as much as possible. 
//leave only necessary operators. 
?> 
<script> 
$(function() { 
<? if($count): ?>window.location.hash = '#comment<?=$id?>'; 
<? else: ?>alert('<?=$alert?>'); 
<? endif ?> 
}); 
</script> 

getone()函數類似於getarr()我在this answer提及,但返回標值,而不是陣列。

0
<?php 
    $param = (isset($_GET['wE']) && is_numeric($_GET['wE']))?"wE":((isset($_GET['sE']) && is_numeric($_GET['sE']))?"sE":false); 
    if($param){ 
     echo showScript($param); 
    } else { 
     //TODO: do something if there's no 'wE' nor 'sE' maybe? 
    } 

    function showScript($param){ 
     if($param == "wE"){ 
      $table = "users_wall"; 
      $alert = "Vägginlägg kunde ej hittas."; 
     } else { 
      $table = "users_statuslog"; 
      $alert = "Status kunde ej hittas."; 
     } 
     $e = mysql_real_escape_string($_GET[$param]); 
     $query_find = "SELECT id FROM ".$table." WHERE id = '".$e."' AND uID = '$showU[id]'"; 
     $query_find = mysql_query($query_find)or die(mysql_error()); 
     $grab_status_comment = (mysql_num_rows($query_find) == 1) ? "window.location.hash = '#comment$e';" : "alert('$alert');"; 
     return '<script>$(function() {'.$grab_wall_comment.'});</script>'; 
    } 
    ?> 

我沒有測試過它......但是這是主要的想法:P

好運,希望這有助於