使用PDO从数据库中提取值

时间:2015-11-12 01:03:01

标签: php mysql api pdo

我有一个问题:如何使用pdo从数据库中提取值? 目前的代码:

$item = $_GET['item'];
$item = str_replace("\"", "", $item);
$item = str_replace("\'", "", $item);
$item = str_replace(" ", "%20", $item);
$item = str_replace("\\", "", $item);
@include_once ("pdocon.php");
$stmt = $dbh->prepare("SELECT * FROM items WHERE name=?");
$stmt->execute(array($item));
$rs = $stmt->fetch(PDO::FETCH_ASSOC);
$stmtt = $dbh->prepare("SELECT auth FROM auth where id=1");
$code = $stmtt->fetch(PDO::FETCH_ASSOC);

我试图从数据库中获取mysql查询“SELECT auth FROM auth where id = 1”的结果。我不知道为什么,但它不起作用。

更新: 好的,这是php文件的整个代码,它提取$ code并将其放在一个API调用的URL链接中。运行这个php后,我一直得到0值。

<?php
$item = $_GET['item'];
$item = str_replace("\"", "", $item);
$item = str_replace("\'", "", $item);
$item = str_replace(" ", "%20", $item);
$item = str_replace("\\", "", $item);
@include_once ("pdocon.php");
$stmt = $dbh->prepare("SELECT * FROM items WHERE name=?");
$stmt->execute(array($item));
$rs = $stmt->fetch(PDO::FETCH_ASSOC);
$stmtt = $dbh->prepare("SELECT auth FROM auth where id=1");
$stmtt->execute(); 
$code = $stmtt->fetch(PDO::FETCH_ASSOC);
if(!empty($rs)) {
        if(time()-$rs["lastupdate"] < 604800) die($rs["cost"]);
}
$link = "https://bitskins.com/api/v1/get_item_price/?api_key=(MYKEYHERE)&code=".$code."&names=".$item."&delimiter=!END!";
$string = file_get_contents($link);
$json = $string;

$obj = json_decode($json);
if($obj->{'status'} == "fail") die("notfound");
$lowest_price = $obj->data->prices[0]->{'price'};
$lowest_price = (float)($lowest_price);
$stmt = $dbh->prepare("UPDATE items SET `cost` = ?,`lastupdate` = ? WHERE `name` = ?");
$stmt->execute(array($lowest_price, time(), $item));
$stmt = $dbh->prepare("INSERT INTO items (`name`,`cost`,`lastupdate`) VALUES (?, ?, ?)");
$stmt->execute(array($item, $lowest_price, time()));
echo $lowest_price;
print_r($lowest_price);
?>

1 个答案:

答案 0 :(得分:6)

您还没有执行$ stmtt,因此没有结果集可以获取。

$stmtt = $dbh->prepare("SELECT auth FROM auth where id=1");
$stmtt->execute();
$code = $stmtt->fetch(PDO::FETCH_ASSOC);