简体   繁体   English

PHP:如何从mySQL数据库中打印值

[英]PHP: How to print value from mySQL database

I'm using php to count the times a link is clicked. 我正在使用php来计算点击链接的次数。

Now, I would like to display that number, but I'm not sure how. 现在,我想显示这个数字,但我不确定如何。

The database is structured like this: 数据库的结构如下:

CREATE TABLE IF NOT EXISTS `count_clicks` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `url` varchar(250) NOT NULL,
  `clicks` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2;

The urls are stored in the database, and called with their id like this: 网址存储在数据库中,并使用其ID进行调用:

<a href="click.php?id=1">Click me</a>

Then it redirects to the url. 然后它重定向到网址。

click.php: click.php:

// get url details based on ID
$sql = "SELECT * FROM " . $SETTINGS["data_table"] . " WHERE id='" . intval($_REQUEST["id"]) . "'";
$sql_result = mysql_query($sql, $connection) or die('request "Could not execute SQL query" ' . $sql);

// check if ID exists
if (mysql_num_rows($sql_result) > 0) {

    $item = mysql_fetch_assoc($sql_result);

    // increase clicks count by one
    $sql = "UPDATE " . $SETTINGS["data_table"] . " SET clicks=clicks+1 WHERE id='" . intval($_REQUEST["id"]) . "'";
    $sql_result = mysql_query($sql, $connection) or die('request "Could not execute SQL query" ' . $sql);

    header("Location: " . $item["url"]);

} else {
    echo "Item is missing.";
}

It works perfectly. 它完美地运作。 But how do I create a php function that will allow me to echo the count for each link? 但是如何创建一个允许我回显每个链接计数的php函数呢? I'm thinking like a function where the argument is the id - it will them return the count... 我想的是一个函数,其中参数是id - 它们将返回计数...

as i see , your are making a redirect when tou add a count, and you can compare first if is an add and make a redirect, and if is not get the counter value from database. 正如我所看到的,当你添加一个计数时,你正在进行重定向,你可以先比较一下是否是一个添加并进行重定向,如果没有从数据库中获取计数器值。 Expect it helps 期待它有所帮助

<?php
//new mysql connection
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');

//select
$sql = "SELECT clicks FROM count_clicks";
foreach ($pdo->query($sql) as $row) {
   echo "Klicks: ".$row['clicks']."<br />";
}
?>

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

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