[英]How can I fetch the number of rows from a database table and insert the total rows into columns of a different table using UPDATE query
I have a table in my database where I want to track the number of downloads for each uploaded file in my website.我的数据库中有一个表,我想在其中跟踪我网站中每个上传文件的下载次数。 I have succeeded in inserting user details after a successful download of a file.
成功下载文件后,我已成功插入用户详细信息。 Each user that downloads a file the user ip address is save in my database tbl (All_downloads) and the filename the user downloaded.
每个下载文件的用户 ip 地址都保存在我的数据库 tbl (All_downloads) 和用户下载的文件名中。 I have a different table (Songs) where I stored all uploaded files and I added a column in the table name "DOWNLOAD COUNTER", now I want to fetch the total number of downloads from tbl ALL_downloads and INSERT the total number into tbl "songs" (I WANT IT TO BE GROUP BY THE SONG NAME).
我有一个不同的表(歌曲),我在其中存储了所有上传的文件,并在表名“DOWNLOAD COUNTER”中添加了一个列,现在我想从 tbl ALL_downloads 获取下载总数并将总数插入到 tbl“songs "(我希望它按歌曲名称分组)。
if (isset($_GET['name']) && basename($_GET['name']) == $_GET['name']) {
$name = $_GET['name'];
$userip = $_SERVER['REMOTE_ADDR'];
$query = "SELECT * FROM songs_download_counter WHERE name='$name' && ip='$userip'";
$result = mysqli_query($con,$query);
if($result->num_rows==0){
$insertquery="INSERT INTO songs_download_counter SETip='$userip', name='$name'";
mysqli_query($con,$insertquery) or die (mysqli_error($con));
} else {
$row=$result->fetch_assoc();
if(!preg_match('/'.$userip.'/i', $row['ip'])) {
$newip = $_SERVER['REMOTE_ADDR'];
$updatequery="UPDATE songs_download_counter SET ip='$newip', name='$name' WHERE name='$name'";
mysqli_query($con,$updatequery) or die (mysqli_error($con));
}
}
The basic query to get your counts is:获取计数的基本查询是:
SELECT count(*)
FROM songs_download_counter
GROUP BY name
The update query looks something like this, depending on the exact name of your songs table:更新查询看起来像这样,具体取决于您的歌曲表的确切名称:
UPDATE
songs
SET
download_counter =
(
SELECT count(*)
FROM songs_download_counter d
WHERE d.name = songs.name
)
See here for some discussion: Update query using Subquery in Sql Server请参阅此处进行一些讨论: 在 Sql 服务器中使用子查询更新查询
Also note: You would be much better off to have a unique ID for each song name and use that for your match instead of the text of the name.另请注意:您最好为每首歌曲名称设置一个唯一 ID,并将其用于匹配,而不是名称的文本。 Matching on names might get you some weird results later as your database grows.
随着数据库的增长,名称匹配可能会在以后为您带来一些奇怪的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.