2014-11-21 42 views
0

当前我有两块数据存储在一个sql数据库中,然后拉入我的网站。我想要的是两条数据被分开存储而不是汇总在一起。mySQL单独存储在表中的数据

所以我安装我的DB像这样:

DROP TABLE IF EXISTS totals; 
    CREATE TABLE totals (
    id int(11) NOT NULL AUTO_INCREMENT, 
    total float NOT NULL, 
    PRIMARY KEY (id) 
) ; 

INSERT INTO totals VALUES (1, 0); 

而且我使用的PHP:

$api = array(); 
$api[] = 'http://api.jo.je/justgiving/data/myuserpage'; 
$api[] = 'http://api.jo.je/justgiving/data/myuserpage2'; 

$total = 0; 

foreach($api as $data) { 

    $open = file_get_contents($data); 

    $feed = json_decode($open); 

    if(is_object($feed)) { 

     $total = $total + $feed->donations_total; 

    } 

} 

// database connection 
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass); // new data 
$id = 1; 
// query 
$sql = "SELECT total 
     from totals 
     WHERE id=?"; 

$q = $conn->prepare($sql); 
$q->execute(array($id)); 

$data = $q->fetch(); 


$total = $data['total']; 

处于这个noobie,我只是需要一些帮助存储两个单独件数据而不是一个。

+0

你在说什么两条数据?他们有关系吗?例? – Steve 2014-11-21 18:55:56

+0

它们是来自两个独立页面的Just Giving API的总捐赠值,目前它们被加在一起 – Doidgey 2014-11-21 18:57:32

+0

需要示例。不是每个人都知道Just Giving是什么 – Steve 2014-11-21 18:58:45

回答

0

我觉得你只是想两个独立在表:

CREATE TABLE totals (
    id int(11) NOT NULL AUTO_INCREMENT, 
    total1 float NOT NULL, 
    total2 float NOT NULL, 
    PRIMARY KEY (id) 
) ; 


$api = array(
    'total1' => 'http://api.jo.je/justgiving/data/myuserpage', 
    'total2' => 'http://api.jo.je/justgiving/data/myuserpage2', 
); 

// The saving part is missing from your code, but it should be something like 
$sql = "UPDATE totals SET {$source}=? WHERE id=?";$q = $conn->prepare($sql); 
$query = $conn->prepare($sql); 
// Note: the above assumes that the "id" already exists. Otherwise 
// you need an "UPSERT" (UPdate or inSERT) that will insert a new value or update 
// it if it already exists. Find more @ this answer: 
// https://stackoverflow.com/questions/15383852/sql-if-exists-update-else-insert-into 

/* 
* Instead of adding up the two API calls' results, we store them separately 
* 
* Of course the value of "id" here must be the same as in the second page, or 
* what you will retrieve will NOT be what you have stored! 
*/ 
foreach($api as $column => $source) {  
    $data = file_get_contents($source); 
    $feed = json_decode($data); 
    if (is_object($feed)) { 
     $value = $feed->donations_total; 
     $query->execute(array($value, $id)); 
    } 
} 

现在在第二页

// query 
$sql = "SELECT total1, total2 from totals WHERE id=?"; 
$q = $conn->prepare($sql); 
$q->execute(array($id)); 

$data = $q->fetch(); 

$total1 = $data['total1']; 
$total2 = $data['total2']; 

This是链接到的答案以上提到)。