PHP:制作更清洁&更短的代码

时间:2010-12-05 15:57:59

标签: 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 ['we']或$ _GET ['se'],以及是否存在。并运行<script>

有没有办法缩短它?我尝试自己做一个布尔值,但也许你可以缩短它?任何想法,因为我希望将来能够更清晰地编码..

2 个答案:

答案 0 :(得分:1)

你不是自己看到的吗?

显然有2个相同的代码部分 您必须将此代码的可变部分变为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()函数类似于我在this answer中提到的getarr(),但是返回标量值而不是数组。

答案 1 :(得分: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

祝你好运,希望这会有所帮助