这是我正在处理的代码,它只返回数据库中的一行
$positions =[];
$rows= query("SELECT symbol,shares from portfolio where id=?",
$_SESSION["id"]);
foreach($rows as $row)
{
$stock =lookup($row["symbol"]);
if($stock!== false){
$positions =[
"symbol" =>$row["symbol"],
"nam" =>$stock["name"],
"shares" => $row["shares"],
"pric" =>$stock["price"],
"total" => $stock["price"] * $row["shares"]
];
}
}
render("portfolio.php",["ways" =>$positions,"title"=>"Portfolio"] );
查找是功能。以下代码适用于portfolio.php
<?php foreach($ways as $position =>$values) : ?>
<th>
<?= $values ?>
</th>
<?php endforeach ?>
下面是在上面(最顶层)代码中声明的查询函数。
function query(/* $sql [, ... ] */)
{
// SQL statement
$sql = func_get_arg(0);
// parameters, if any
$parameters = array_slice(func_get_args(), 1);
// try to connect to database
static $handle;
if (!isset($handle))
{
try
{
// connect to database
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
// ensure that PDO::prepare returns false when passed invalid SQL
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
// trigger (big, orange) error
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
}
// prepare SQL statement
$statement = $handle->prepare($sql);
if ($statement === false)
{
// trigger (big, orange) error
trigger_error($handle->errorInfo()[2], E_USER_ERROR);
exit;
}
// execute SQL statement
$results = $statement->execute($parameters);
// return result set's rows, if any
if ($results !== false)
{
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
else
{
return false;
}
}
答案 0 :(得分:2)
因为在SQL中您定义的特定ID通常只能是一个
i.e. where id=?
因此,如果您需要更多结果,则必须扩展标准
e.g. WHERE id > 5 AND id < 10