Edgardasun
Edgardasun

Reputation: 81

Php MySQL How to Updated/Insert into a database row

Table_A

+--------+-----------+---------+
|   id   |   name    |  views  |
+--------+-----------++--------+
|   num  | text      |   int   |
+--------+-----------+---------+
|    1   | Video 1   |  10     |
|  NULL  | NULL      |  0      |
|  NULL  | NULL      |  0      |
|  NULL  | NULL      |  0      |
|  NULL  | NULL      |  0      |
+--------+-----------+---------+

<a href="video.php?id=video1&idtitle=Hello%20Video1"> 
<a href="video.php?id=video2&idtitle=Hello%20Video2">
<a href="video.php?id=video3&idtitle=Hello%20Video3">

I'm trying to make the script do something like this.

1.User click on link
2.User is on video.php?id=video1
3.Mysql then add a +1 to my id column #1
4.then take the video title from $videoName
5.Mysql take the title inside of $videoname and store it on name column #2
6.Mysql then add +1 to Views everytime ID 1 is view
7.Mysql is now finish with Row 1
8.Now Mysql will repeat that same step if video.php?id=video2 and so on,

How can i make this happen?

  $id = $_GET['id'];
  $videoName = $_GET['idtitle'];
  $pdo = new PDO('mysql:localhost;dbname=videocount', 'root', '');
  $userip = $_SERVER["REMOTE_ADDR"];

  if($userip){
  $pdo->query("UPDATE Table_A SET (`id`, `name`, `views`)
  VALUES (NULL,$videoName, views+1)");
  }

I also try the code below but still no luck.

  if($userip){
  $pdo->query("INSERT INTO `videocount`.`Table_A` (`id`, `name`, `views`)
  VALUES (NULL, '$videoname', 'views'+1)");
  }

Upvotes: 0

Views: 169

Answers (2)

fusion3k
fusion3k

Reputation: 11689

UPDATE instead of UPDATED, VALUES instead of VALUE. In addition you have to add a WHERE condition to your query to select record to update.

This is another correct syntax:

$pdo->query( "UPDATE `Table_A` SET `views`=`views`+1 WHERE `id`='$id'" );

Edit:

To update also the video name you can perform this query:

$pdo->query( "UPDATE `Table_A` SET `name`='{$videoName}', `views`=`views`+1 WHERE `id`='$id'" );

On the border, you should bind the variable values to avoid errors with titles special characters.

See more about binding and MySQL UPDATE syntax

Upvotes: 2

Xiaosong Guo
Xiaosong Guo

Reputation: 495

I think there is a little confusion about data view logic.

First of all, you need to save all data into database, then list them for user. When the use click the link to view this video, the column of views need to be updated.

Upvotes: 1

Related Questions