目前我有两个数据存储在sql 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 :(得分: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是上述答案的链接。)