简体   繁体   中英

How to assign the results of a row to different variables using PDO in PHP & MySQL

I have a table

id    url    count
1     www.    6
2     www.    9
3     www.    11
4

and so on

I want to display the count next to a link in my webpage and therefore I am using the statements below to assign "count" to a variable for a specific id.

$stmt1 = $db->query("SELECT * FROM clickcounter WHERE id = 1");
while ($row = $stmt1->fetch(PDO::FETCH_ASSOC)){
$count1=$row['count'];
}
$stmt2 = $db->query("SELECT * FROM clickcounter WHERE id = 2");
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)){
$count2=$row['count'];
}
$stmt3 = $db->query("SELECT * FROM clickcounter WHERE id = 3");
while ($row = $stmt3->fetch(PDO::FETCH_ASSOC)){
$count3=$row['count'];
}

and so on

I have plenty of id in my table. Is there a better way to do this or do I have to write these statements over and over again.

Basically I want to assign the values of "count" to a variable so that I can use them in my webpage at different locations.

Ok, you can make a block with url list and add pager with button "next list" or so.

For example:

$page = (isset($_GET['page']) && is_numeric($_GET['page'])) ? $_GET['page'] : 0;
$per_page = 10;
$url_list = "";
$stmt = $db->query("SELECT * FROM clickcounter LIMIT ".($page * $per_page).", 10");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$url_list .= $row['url']." : ".$row['count']."<br />\n";
}

// view url list

print $url_list;

You can save it in external file and use javascript (like jQuery) for display it in you page and change pages with "onclick" function :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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