Insert query not working with MySQL - php

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')");

Related

Whats wrong in my php mysql counter script code?

I am writing a Php 5 and Mysql 5 page counter script. When a student having id as 'visitorid' visits a page having id 'pageid' (both int(11)) the page counter tries to log the visit in 'visitors' database. But counter is not updating in mysql db, instead the visit_counter int(4) turns to 0.Whats wrong with my code? visitdate is datetime.
<?php
$pageid = 101;
$visitorid = 234;
$sql = "SELECT * FROM visitors
WHERE pageid = ".$pageid."
AND visitorid = ".$visitorid;
$temp = mysql_query($sql) or die("Error 1.<br>".mysql_error());
$data = mysql_fetch_array($temp);
// visit_counter is a field in table
if(($data['visit_counter']) != NULL){
echo "Entery exists <br>";
// Tried below version also
$visit = " SET visit_counter = visit_counter+1";
//$visit_counter = $data['visit_counter'];
//$visit = " SET visit_counter = ".$visit_counter++ ;
// Valid SQL
// UPDATE `visitors`
// SET visit_counter = visit_counter+1
// WHERE pageid = 101 and visitorid=234
// This manual sql query updates in phpmyadmin
$sql = "UPDATE visitors ".$visit."
AND visitdate = NOW()
WHERE pageid = ".$pageid."
AND visitorid = ".$visitorid;
$temp = mysql_query($sql) or die("ERROR 3.<br>".mysql_error());
//No error is displayed on above query.
} else {
//first entry
$visit_count = "1";
$sql = "INSERT INTO visitors
(`pageid`,`visitorid`, `visitdate`, `visit_counter`)
VALUES ('".$pageid."','".$visitorid."', NOW(), '".$visit_count."')";
$temp = mysql_query($sql);
//first entry is inserted successfully
//and visit_counter shows 1 as entry.
}
?>
Can anyone tell me whats wrong with this code?
Oh! I got answer by myself. Sometimes just little errors make us go crazy..
I made a mistake in udate query.. rather than using and I should have user a comma instead. .. working well now!

Calling a function for each MySQL row

I have a standard MySQL database, with around 60 rows (as in user accounts). When I first made it I made the mistake of making session IDs the same as the simple account ID, now I want to fix my mistake and I am obviously not going to go through 60 rows to reset them different secure session IDs, so I am writing this function:
function generate_sessionid(){
return bin2hex(openssl_random_pseudo_bytes(32));
}
function assign_all_sessionids(){
$sessionid = generate_sessionid();
$conn = sql_connect();
$result = mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE 1");
sql_disconnect($conn);
}
assign_all_sessionids();
Problem: Every account in the database gets the same random session ID as the rest. How do I make it recall the function for each row in order to allow it to be random for each row?
Try get user's count from DB and simply execute it N times
function assign_all_sessionids(){
$conn = sql_connect();
// getting users count
// here just change 'id' to your id parameter
$result = mysqli_query($conn, "SELECT id FROM accounts");
$arr = $result->fetch_array(MYSQLI_NUM);
// executing N times
for($i = 0; $i < $result->num_rows; $i++){
$sessionid = generate_sessionid();
// here just change 'id' to your id parameter again
mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE `id`=".$arr[$i]);
}
sql_disconnect($conn);
}
You can do what you want by first setting all the session ids to NULL:
UPDATE accounts
SET sessionid = NULL;
Then, inside the loop:
UPDATE accounts
SET sessionid = '$sessionid'
WHERE sessionid IS NOT NULL
LIMIT 1;
Normally you don't want to execute queries in a loop, however in this case you need to get all of the current unique identifiers, loop and generate a new identifier and then update one:
function assign_all_sessionids(){
$conn = mysqli_connect('whatever...');
$select = mysqli_query($conn, "SELECT sessionid FROM accounts");
while(list($id) = mysqli_fetch_assoc($select)) {
$sessionid = generate_sessionid();
$update = mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE sessionid='$id'");
}
}

Make hit counter per user profile on PDO

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']++;

Database not updating row

Before you assume I didn't establish a database connection, I did. the only portion of the code that does not update is the if empty statements.
All the values can be echoed out correctly, it's just that query doesn't work.
This is in directory config and named stuff.php
$user = $mysqli->real_escape_string($_SESSION['username']);
$user_query = "SELECT * FROM users WHERE username = '$user'";
$result = $mysqli->query($user_query);
$row = $result->fetch_assoc();
$referrer = $row['ref'];
$refearn = $row['refearn'];
verify.php
include('config/stuff.php');
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { // Get Real IP
$IP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$IP = $_SERVER['REMOTE_ADDR'];
}
if ($IP=="external server ip here") {
if (!empty($referrer)){
$mysqli->query("UPDATE users SET points=points+10, refearn = refearn+10 WHERE username='".$referrer."'") or die(mysqli_error($mysqli));
}
$mysqli->query("UPDATE users SET points=points+".$earnings.", completed = completed+1 WHERE username='".$subid."'") or die(mysqli_error($mysqli));
}
My guess is you could try to retrieve the value of points through a query then add to it so you're just updating to a simple value. However, if mysql_error() is returning an error, it should be easier to figure out.
Example:
$getPoints = mysql_query("SELECT points FROM table WHERE condition");
$points = mysql_result($getPoints, 0, "points");
$update = mysql_query("UPDATE table SET points=" . ($points+10) . " WHERE condition");
Hope that helps. Another consideration, though. Why use an endif structure unless you're breaking PHP tags to display content?
try this:
$mysqli->query("UPDATE `users` SET `points`=`points`+10, `refearn` = `refearn`+10 WHERE `username`='".$referrer."'") or die(mysqli_error($mysqli));
Hope this helps. What I think is, mysql query might be taking those as constant - not as the mysql rows. Try that

Add value to a user not logged in using php

I have a table (users) with various users. if you refer someone to register it creates a referal id in a field (refcode) similar to your (id) in his/her profile. now when he/she is logged in, i want to add value to the referal's profile.
So basically i need to add value to a user not logged in.
here is my code.
$sql="SELECT * FROM users";
$val=(2);
$result=mysql_query($sql,$bd);
$data=mysql_fetch_assoc($result);
while ($array = mysql_fetch_array($result)) {
// equate the value to a variable to use outside
// this while loop
$acc_balance = $array['com_balance'];
$comm = $array {$_SESSION['refcode']};
$commision = $array['id'];
}
$remainder = $acc_balance + $val;
$update_query = mysql_query("UPDATE users SET com_balance = '". mysql_real_escape_string($remainder) ."'
WHERE id=refcode");
if ($update_query) {
print ""
A bunch of changes, marked by numbers:
$sql="SELECT * FROM users where userID='$_SESSION['refcode']'"; //#1
$val = 2; //#2 : Why do u need the ()?
$result = mysql_query($sql,$bd);
$data=mysql_fetch_assoc($result);
while ($array = mysql_fetch_array($result)) {
// equate the value to a variable to use outside
// this while loop
$acc_balance = $array['com_balance'];
$comm = $array{$_SESSION['refcode']}; //#3: I am not sure what you're doing here?
$commision = $array['id'];
}
$remainder = $acc_balance + $val;
$update_query = mysql_query("UPDATE users SET com_balance = '". mysql_real_escape_string($remainder) ."'
WHERE id=refcode"); // #4: where are you defining refcode? if variable, the query needs to be WHERE id='$refcode'");
if ($update_query) {
print "Update successful";
Firstly, change:
$sql="SELECT * FROM users";
as you do not need to loop through an entire table just to get the details of the user logged in. Something like this should do the trick:
$yourID=3;// Assume this is sanitized data from a cookie or a login script.
$sql="SELECT * FROM users where userID=$yourID";
Secondly, when you verify the login of the user who referred the next user, just add in a query like this:
$update_query = mysql_query("
UPDATE users SET
com_balance = (select * from (
select com_balance from users where id=$yourID))");
This will update the new user with the balance from the referring user (which seems to be what you want). You will need to use the double subquery to get past the annoying mysql bug/feature where it cannot update a table from a subquery on the same table unless you encapsulate it in a second subquery.

Categories