简体   繁体   English

将 SQL 查询结果插入到单独的 PHP 变量中

[英]Insert SQL query results into separate PHP variables

I'm trying to make an ad system with PHP pdo.我正在尝试使用 PHP pdo 制作广告系统。 How can I get result id's of the following SQL query into my PHP variables?如何将以下 SQL 查询的结果 ID 放入我的 PHP 变量中?

SELECT id FROM ads, ( SELECT id AS sid FROM ads WHERE position="A" ORDER BY RAND( ) LIMIT 5 ) tmp WHERE ads.id = tmp.sid

I just don't know how to get those values in the variables like this:我只是不知道如何在这样的变量中获取这些值:

$ad_1 = result[1]
$ad_2 = result[2]
$ad_3 = result[3]
$ad_4 = result[4]
$ad_5 = result[5]

With the help of those variables ($ad_1...5) I could display unique and random ads in different places, get correct data, and update ad clicks/views...在这些变量 ($ad_1...5) 的帮助下,我可以在不同的地方展示独特和随机的广告,获取正确的数据,并更新广告点击/浏览...

try this :尝试这个 :

$begin = "ad_";
for($i = 0; $i < 6 ; $i++) {
    $($begin.$i) = $result[$i];
}

(assuming you array $result is previously defined) (假设您之前定义了数组$result

Best to get into the habit of using prepared statements like this:最好养成使用这样的准备好的语句的习惯:

<?php
$adIds = array();
$position = 'A'; // probably set dynamicaly
$stmt = $dbh->prepare("SELECT id FROM ads, ( SELECT id AS sid FROM ads WHERE position=? ORDER BY RAND( ) LIMIT 5 ) tmp WHERE ads.id = tmp.sid");
$stmt->bindParam(1, $position);
if ($stmt->execute()) {
  while ($row = $stmt->fetch()) {
    $adIds[] = $row[0];
  }
}
?>

$adIds is now an array containing all the ids returned from the select statement. $adIds现在是一个包含从 select 语句返回的所有 id 的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM