[英]Turning a result from a query into a PHP variable
下面的查詢在頁面上,其中$submissionid
只有一個值。 因此,場points
僅具有一個值。
如何將下面查詢中的points
轉換為常規PHP變量?
$sqlStra = "SELECT points, submissionid
FROM submission
WHERE submissionid = '$submissionid'";
編輯:這是從MySQL數據庫中提取的。
編輯II:我要points
等於整個頁面上的變量,而不僅僅是在while循環內。
這樣,您可以讀取查詢返回的所有點。
while ($row = mysql_fetch_array($sqlStra, MYSQL_ASSOC)) {
$points = $row["points"]);
}
我將使用ORM庫(我使用Kohana附帶的庫)來消除SQL注入的可能性。 但是,假設已經建立了數據庫連接,則此代碼將執行您要查找的操作。
$resource = mysql_query("SELECT points, submissionid FROM submission WHERE submissionid = '$submissionid'");
$result = mysql_fetch_assoc($resource);
echo $result["points"];
如果您尚未建立MySQL數據庫連接,請簽出mysql_connect 。
好吧,您需要從該查詢中獲取資源,然后將其提供給mysql_fetch_assoc,如下所示:
$res = mysql_query($sqlStra);
// If you **Know for sure** you'll only have one row:
$row = mysql_fetch_assoc($res);
$points = $row['points'];
//Otherwise, you're going to need to loop.
$array_of_all_points = array();
while ($row = mysql_fetch_assoc($res)) {
// $row['points'] now has what you want. You can assign it normally, or can use
// extract($row) to turn it into $points, which I would advise against personally.
$points = $row['points'];
$array_of_all_points[$row['submissionid']] = $row['points'];
}
echo $points; // This will be the last $row['points'] that was executed.
echo $array_of_all_points['thatsubmissionid']; // Will output the points for the given session id.
此外,該查詢也不安全(如果$ submissionid來自用戶輸入,則容易受到SQL注入的攻擊),您應該使用iloveitaly提到的ORM庫。 (我使用Zend DB ,盡管從技術上講它並不是ORM本身)
編輯:
正如評論所指出的,這取決於您是否實際使用Mysql。 如果不是,則可以使用PDO庫進行查詢。
$sqlStra = "SELECT points FROM submission WHERE submissionid = ?";
$statement = $connection->prepare($sqlStra);
$statement->bind_param('i', $submissionid);
$statement->bind_result($points);
$statement->execute();
$statement->fetch(); // this will create / populate $points
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.