Make hit counter per user profile on PDO - php

I have a problem with this code for make a hit counter per user profile on PDO (MYSQL), on page loads not update and not show the counter, only text "Visits:", the value remains at "0".
$id = $profile_data['username'];
$statement = $db->query("SELECT `visits` FROM `users` WHERE id='$id'");
$record = $statement->fetchAll();
if(sizeof($record) != 0)
{
$counter = $record[0]['counter']++;
$db->exec("UPDATE `users` SET visits='$counter' WHERE id='$id'");
echo "Visits: " .$counter;
}
else
{
$db->exec("INSERT INTO `users` (id, visits) VALUES ('$id', 1)");
echo "Visits: 1";
}

Since you pulling the fields visits from the database, you need to change:
$counter = $record[0]['counter']++;
to:
$counter = $record[0]['visits']++;

Related

Duplicate entry '1' for key 'PRIMARY' when updating the table

I have a problem when trying to update table after checking row. Not sure if the "if" statement is wrong, however I'm not quite sure, why the UPDATE sql is returning this error. I wouldn't be suprised if INSERT did that.
Here's part of code:
$sql = "SELECT user_id FROM players WHERE user_id = '$id'";
$result = $connect->query($sql);
if($result->num_rows > 0)
{
$sql = "UPDATE players SET user_id = '$Player->user_id', display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
if($connect->query($sql) === TRUE)
{
echo 'Table has been successfully updated.';
}else{
echo 'There has been a problem with updating the "players" table. <br>Error: '.$connect->error;
}
}else{
$sql = "INSERT INTO players(user_id, display_name, attackPower, defensePower) VALUES('$Player->user_id', '$Player->display_name', '$Player->attackPower', '$Player->defensePower')";
if($connect->query($sql) === TRUE)
{
echo'Table has been successfully migrated.';
}else{
echo'Table migration has failed.';
}
}
$connect->close();
INSERTing is working just fine. I would appreciate any advice. Thanks.
Your update query should look like:
$sql = "UPDATE `players` SET `display_name` = '{$Player->display_name}',
`attackPower` = '{$Player->attackPower}', `defensePower` = '{$Player->defensePower'}
WHERE `user_id` = '{$Player->user_id}'";
It cause an error because Identity columns are not updateable.
You can update every columns except them:
$sql = "UPDATE players SET display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
As #aynber and #Julqas said, problem was my sql was missing WHERE condition. Thanks for help.

How to record one vote per user php

So I am trying to write a php script that records one vote increment per user. Voters a are presented with a list of prospective candidates then clicks once on their name.
Now on attempt of a second time i hope to get a notification allowing this action. Please help.
<?php
if(isset($_POST['vote']))
{
$sql3='INSERT INTO sessions (memberID, postid, email, voted) VALUES ("","", "", 1;)';
$result3 = mysqli_query($con, $sql3);
}
// $count = mysqli_num_rows($result2);
$candidate_name = null;
$vote = $_POST['vote'];
mysqli_query($con, "UPDATE tbCandidates SET candidate_votes=candidate_votes+1 WHERE position_id='$vote'");
// $count = mysqli_num_rows($result2);
if ( $count<1) {
//$sql3='INSERT INTO sessions (memberID, postid, voted) VALUES ("", memberbers.memberID,"1")';
//$result = mysqlI_query("select id from Users where username ='".$_SESSION['email']."'");
//$result = mysqli_query($con, $sql3);
// $count = mysqli_num_rows($result2);
} else {
echo"You have voted already";
}
Put a "unique" flag on your memberID column in your SQL table. In that case when you try to insert a new row with the same memberID, it will not work.
Then catch the SQL write fail, and display a message if it gets to it.

Show error message when clicked on the like button

Hello I want to make a like system using PHP and MySQL when clicked on the like Button i also insert Data in the database but there is an error database value inserted but like value as 0 no increment and undefined error occurs . Can anybody help me solving this problem
There is my Like button code :
<?php
//// work with like box
$get_likes = mysqli_query($con,"SELECT * FROM `likes`");
if (mysqli_num_rows($get_likes)===1) {
$get = mysqli_fetch_assoc($get_likes);
// $uid = $get['uid'];
$total_likes = $get['total_likes'];
//echo $uid;
$total_likes = $total_likes + 1;
//echo $total_likes++;
}
if (isset($_POST['likebutton_'])) {
$like = mysqli_query($con,"UPDATE `likes` SET `total_likes` = '$total_likes'") or die(mysqli_error($con));
//$insert_Data = mysqli_query($con,"INSERT INTO `likes` (`uid`) VALUES('$username')") or die(mysqli_error($ocn));
header("Location:home.php");
}
else
{
echo "Error";
}
?>
this code work fine without insert Data
There is My liked with Data Insertd Code
<?php
////work with like box
$get_likes = mysqli_query($con,"SELECT * FROM `likes`");
if (mysqli_num_rows($get_likes)===1) {
$get = mysqli_fetch_assoc($get_likes);
// $uid = $get['uid'];
$total_likes = $get['total_likes'];
//echo $uid;
$total_likes = $total_likes + 1;
//echo $total_likes++;
}
if (isset($_POST['likebutton_'])) {
$like = mysqli_query($con,"UPDATE `likes` SET `total_likes` = '$total_likes'") or die(mysqli_error($con));
$insert_Data = mysqli_query($con,"INSERT INTO `likes` (`uid`) VALUES('$username')") or die(mysqli_error($ocn));
header("Location:home.php");
}
else
{
echo "Error";
}
?>
this is output i want to display my font-end page <?php echo $total_likes ;?> but it occur error
The error is Undefined Variable
I also try $total_likes="";
as global but still not work
Your code suffers from a race condition. What you should be doing is this pattern:
INSERT INTO likes (uid, total_likes) VALUES (?, 1)
ON DUPLICATE KEY SET total_likes=total_likes+1
Where you use bind_param to set the placeholder value to your UID.
Note that in your one query you set the total count of all likes to be +1. This is a huge mistake.

Insert query not working with MySQL

I don't know if wrote something wrong in the query, or if it's a logic error. The problem is on the second to last line.
<?php
include "connectdb.php";
$userId = mysql_real_escape_string($_GET["userId"]);
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='userId'");
$num = mysql_num_rows($q1);
if($num==1){
//user exists, update visits and unique values
$visits = 0;
while($row=mysql_fetch_array($q1)){
$visits = $row["visits"] + 1;
echo $row["visits"] + 1;
}
mysql_query("UPDATE visitors SET visits='$visits',unique='no' WHERE userId='$userId'");
die();
}
//if there is no current visitor
mysql_query("INSERT INTO visitors(userId,visits,unique) VALUES('$userId','1','yes')");
?>
EDIT: userId and visits are both set to INT in the database.
i think first error in in variable name using in $ql and second is $num==1 if in visitors table multiple record of thats user then this condition will be wrong ($num==1) so i think replace it with this ($num>0)
<?php
include "connectdb.php";
$userId = mysql_real_escape_string($_GET["userId"]);
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='$userId' ");
$num = mysql_num_rows($q1);
if($num>0)
{
//user exists, update visits and unique values
$visits = 0;
while($row=mysql_fetch_array($q1))
{
$visits = $row["visits"] + 1;
echo $row["visits"] + 1;
}
mysql_query("UPDATE visitors SET visits='$visits',unique='no' WHERE userId='$userId'");
die();
}
//if there is no current visitor
mysql_query("INSERT INTO visitors(`userId`,`visits`,`unique`) VALUES ('$userId','1','yes') ");
?>
You should add error handling to your sql queries, but the problem (after the correction indicated by #DanielLisik) is the use of a reserved word: unique.
Change your query to:
mysql_query("INSERT INTO visitors(userId,visits,`unique`) VALUES('$userId','1','yes')");
You should also consider changing to PDO or mysqli as the mysql_* functions are deprecated.
1.
Change:
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='userId'");
to:
$q1 = mysql_query("SELECT * FROM visitors WHERE userId=$userId");
2.
Delete the single quotes around $userId in your SQL queries (since it's an INT). It should be like this:
mysql_query("UPDATE visitors SET visits='$visits',`unique`='no' WHERE userId=$userId");
and:
mysql_query("INSERT INTO visitors(userId,visits,`unique`) VALUES($userId,'1','yes')");

Why this if else condition is not working properly?

I am using if else condition with foreach loop to check and insert new tags.
but both the conditions(if and alse) are being applied at the same time irrespective of wether the mysql found id is equal or not equal to the foreach posted ID. Plz help
$new_tags = $_POST['new_tags']; //forget the mysl security for the time being
foreach ($new_tags as $fnew_tags)
{
$sqlq = mysqli_query($db3->connection, "select * from o4_tags limit 1");
while($rowq = mysqli_fetch_array($sqlq)) {
$id = $rowq['id'];
if($id == $fnew_tags) { //if ID of the tag is matched then do not insert the new tags but only add the user refrence to that ID
mysqli_query($db3->connection, "insert into user_interests(uid,tag_name,exp_tags) values('$session->userid','$fnew_tags','1')");
}
else
{ //if ID of the tag is not matched then insert the new tags as well as add the user refrence to that ID
$r = mysqli_query($db3->connection, "insert into o4_tags(tag_name,ug_tags,exp_tags) values('$fnew_tags','1','1')");
$mid_ne = mysqli_insert_id($db3->connection);
mysqli_query($db3->connection, "insert into user_interests(uid,tag_name,exp_tags) values('$session->userid','$mid_ne','1')");
}
}
}
i think you are inserting
$r = mysqli_query($db3->connection, "insert into o4_tags(tag_name,ug_tags,exp_tags)
values('$fnew_tags','1','1')");$mid_ne = mysqli_insert_id($db3->connection);
and then you are using while($rowq = mysqli_fetch_array($sqlq))
which now has records you just inserted therefore your if is executed
I'm pretty sure the select query below will always return the same record.
$sqlq = mysqli_query($db3->connection, "select * from o4_tags limit 1");
I think most of the time it will goes to the else, which execute the 2 insert.
Shouldn't you write the query like below?
select * from o4_tags where id = $fnew_tags limit 1

Categories