获取数据无效

时间:2015-08-12 06:19:18

标签: php mysql json xml

我面临的问题是当我点击http://www.localhost/test1.php?user=10&num=10时 无论num = 10& user = 10。它显示数据库中的所有数据。如何获得关于num或user的特定数据,例如num = 5或6?

<?php
/* require the user as the parameter */
if(isset($_GET['user']) && intval($_GET['user'])) {

    /* soak in the passed variable or set our own */
    $number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
    $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
    $user_id = intval($_GET['user']); //no default

    /* connect to the db */
    $link = mysql_connect('localhost','username','pwd') or die('Cannot connect to the DB');
    mysql_select_db('marketing',$link) or die('Cannot select the DB');

    /* grab the posts from the db */
    $query = "SELECT * FROM data";
    $result = mysql_query($query,$link) or die('Errant query:  '.$query);

    /* create one master array of the records */
    $posts = array();
    if(mysql_num_rows($result)) {
        while($post = mysql_fetch_assoc($result)) {
            $posts[] = array('post'=>$post);
        }
    }

    /* output in necessary format */
    if($format == 'json') {
        header('Content-type: application/json');
        echo json_encode(array('posts'=>$posts));
    }
    else {
        header('Content-type: text/xml');
        echo '<posts>';
        foreach($posts as $index => $post) {
            if(is_array($post)) {
                foreach($post as $key => $value) {
                    echo '<',$key,'>';
                    if(is_array($value)) {
                        foreach($value as $tag => $val) {
                            echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
                        }
                    }
                    echo '</',$key,'>';
                }
            }
        }
        echo '</posts>';
    }

    /* disconnect from the db */
    @mysql_close($link);
}
?>

1 个答案:

答案 0 :(得分:0)

为了将2列的总和自动保存到第3列,您有2个选项: 1.直接从代码中保存 2.创建一个触发器。

如果你想要一个触发器 - 这里是触发器

CREATE TRIGGER ins_sum BEFORE INSERT ON user
FOR EACH ROW SET NEW.s3 = NEW.s1+NEW.s2;

参考详细说明: https://dev.mysql.com/doc/refman/5.5/en/trigger-syntax.html

从代码中:

INSERT INTO users (s1,s2,s3) values (val1, val2, val1+val2)

当然,您应该将val1和val2更改为实际值。