I have a users table where I want to update the scores each time a user finishes the game. Unityscript part is working fine but after I post the score to the database it appears doubled or tripled. I post the score as int and also the table column is of int format. My PHP looks like this:
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = array(
':username' => $_POST['username'],
':score' => $_POST['score']);
$statement = $db -> prepare ("UPDATE users SET score = score + :score
WHERE username = :username");
$statement->execute($data);
}
catch(PDOException $e) {
echo $e->getMessage();
}
Any help or advice is appreciated.
You are using prepared statements, but you are still allowing injection by directly implementing the $score variable. Do the same thing with score that you did with username.
What do you mean by double or triple? Do you mean that the number is two or three times bigger? If so, try using a SELECT statement to fetch the score and do the math in PHP. Then, UPDATE the users table.
Doing this will allow you to better understand what you are doing wrong. Have you tried echoing the value of score within your try and catch to see if the value repeats? The code may be running more than once.
$statement = $db -> prepare ("UPDATE users SET score = :score
WHERE username = :username");
use this, i think it will work
Related
The following is my code
try {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$sql = "UPDATE usermaster SET Password=?, UserName=?, OwnerOrEmp=?, DBName=?, DeleteFlag=?, UpdateDate=? WHERE UserId = ?";
$sql = "UPDATE usermaster SET Password=:password, UserName=:userName, OwnerOrEmp=:ownerOrEmp, DBName=:dBName, DeleteFlag=:deleteFlag, UpdateDate=:updateDate WHERE UserId = :id";
$q = $pdo->prepare($sql);
$q->bindParam(':id', $id, PDO::PARAM_STR, 8);
$q->bindParam(':userName', $name);
$q->bindParam(':password', $pass);
$q->bindParam(':ownerOrEmp', $ownEmp);
$q->bindParam(':dBName', $dbName);
$q->bindParam(':deleteFlag', $delEmp);
$q->bindParam(':updateDate', $curr_date);
$q = $pdo->prepare($sql);
$q->execute(array($pass,$name,$ownEmp,$dbName,$delEmp,$curr_date, $id));
Database::connect();
}catch(PDOException $e){
//die($e->getMessage());
$db_error = "".$e->getMessage();
}
header("Location: ShainIndex.php");
}
Request your kind insight, this piece of code alone does not get executed and update is not executed...Thanks in advance.
your preparing same query twice
$q->bindParam(':updateDate', $curr_date);
// $q = $pdo->prepare($sql); //comment this line
$q->execute(array($pass,$name,$ownEmp,$dbName,$delEmp,$curr_date, $id));
I finally began to debug each and every single variables value being inserted, as shown in the above bindParam(). It turned out that by default or due to some string handling there happened to a space(" ") being inserted into many many of the values of those variables.
So, what this space was causing was, that it did not allow the value to be matched on the database to the inputed data coming from the view.
Due to which especially the "id" field receive values with spaces...like " 00100001" although it is not easily visible it never matched with "00100001" value in the db's table.
Thus, this took me the whole day and almost cost me my job. In some place a small "-" broke down an entire satellite launching rocket.
So, I am in a way blogging my "Word of Caution" to all those whose life ticks on one tiny bit of characters.
Thanks to all those who provided their valuable inputs and time.
So I'm new to php and mysql and over the past few days have created a log in system using php and mysql. I am trying to make a function where a user can change their password with the following query:
$query2 = mysql_query("SELECT password FROM adminusr WHERE id =$idToChange");
$result = mysql_query($query2) or die($idToChange.mysql_error());
With SELECT statements you only select rows. To change them you need UPDATE. Consider using PDO because mysql_* functions are deprecated. Also try to hash your passwords and don't store them in plain text.
You need something like this:
$query2 = mysql_query("UPDATE adminusr SET password = '$new_password' WHERE id = '$idToChange'");
Using PDO
//Make the connection using PDO
try {
$conn = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
echo "PDO connection object created";
}
catch(PDOException $e) {
echo $e->getMessage();
}
//Make your query
$sql = 'UPDATE adminusr SET password = :new_password WHERE id = :id';
$stmt = $conn->prepare($sql);
$stmt->execute(array(':new_password'=>$new_password, ':id'=>$idToChange));
EDIT answering to comment
Then you need to have also username and password fields at your form. So, you need four fields: username, oldPassword, newPassword, confirmNewPassword. Before the update statement you need to select the user having credentials username, oldPassword. If you find only one then you have to check if newPassword and confirmNewPassword match. If match then proceed to update. Otherwise print some error message.
I'm used to using BindParam() and since this is a SELECT query Param's are not related. Basically I'm trying to make a notification system that will check the database and if any of the rows' status is '0' then it would output all the rows information.
I have the following columns: id, api, request, apikey, apiemail, keyauth, ip, dateandtime, status.
How would I make PDO put all the information it gathers from all rows with status='0' and put them into usable variables like: $id, $api, $request? Of course there could be more then one row with status='0' so maybe have the variables arrays and output like $id[0], $id[1] e.t.c.
PDO:
<?php
include('/cdn/global/db.php');
$opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION );
$dsn = "mysql:host=$host;dbname=$dbname";
$DBH = new PDO($dsn, $username, $password, $opt);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$STH = $DBH->prepare("SELECT id, api, request, apikey, apiemail, keyauth, ip, dateandtime, status FROM apirequests WHERE status = 0");
$STH->execute();
echo "<p>The link is now in Queue, An admin will check the link soon!</p>";
# close the connection
$DBH = null;
######
?>
You can fetch them as objects(Also order by a field if you want the results in a specific order):
$STH = $DBH->prepare("SELECT id, api, request, apikey, apiemail, keyauth, ip, dateandtime, status FROM apirequests WHERE status = 0 ORDER BY id");
$STH->execute();
if($STH->rowCount()){
while($row = $STH->fetch(PDO::FETCH_OBJ)){
#Perform whatever operation you need on a single row
echo "$row->id, $row->api, $row->request, $row->apikey, $row->apiemail\n";
}
}
put them into usable variables like: $id, $api, $request e.t.c
There is no point in doing that. $row['id'] is no less usable but WAY more flexible. Although you can use extract() function to assign array members to corresponding variables.
of course there could be more then one row with status='0' so maybe have the variables arrays and output like $id[0], $id[1] e.t.c
This would make even less sense and nobody is doing it this way. Anyways, PDO won't make such variables for you. Instead, array of rows have to be used, like shown in other answers.
$value = 0;
$STH = $DBH->prepare("SELECT id, api, request, apikey, apiemail, keyauth, ip, dateandtime, status FROM apirequests WHERE status = ?");
$STH->execute(array($value));
$variable[] = $STH->fetchAll(PDO::FETCH_ASSOC);
$id=$_GET['previd'];
$SQL = "select * from pro where prId=".$id;
I am new to PHP. Can anyone explain what happens here?
This is taking the value of the GET (url) passed variable "previd".
Something like http://example.com/page.php?previd=123 would set
previd to 123.
Next it sets the variable $id to 123.
Next $SQL gets set to select * from pro where prId=123
Next a nefarious person can go to http://example.com/page.php?previd=;DROP TABLE pro and your database has now been deleted.
This is why people use sanitization and prepared statements.
// PDO + MySQL
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT some_field FROM some_table");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['some_field']);
More Info
I executing the following code which creates a company_id as a UUID_SHORT in a temporary table.
This company_id will then be used to insert records in multiple tables with the UUID as the primary key. My issue is when I try retrieve the company_id that is $company_id in my code it is null. However if I json_encode ($tempResult) the company_id value is there. What am I doing wrong?
Any help is much appreciated, thank you!
try {
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $db->id, $db->pass); //connect to db
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //error modes
$temp = $conn->prepare('CREATE TEMPORARY TABLE tempId (user_id VARCHAR(17) PRIMARY KEY, company_id VARCHAR(17))');
$temp->execute();
$temp = $conn->prepare('INSERT INTO tempId(user_id, company_id) VALUES(:user_id, UUID_SHORT())');
$temp->bindParam(':user_id', $_SESSION['username'], PDO::PARAM_INT);
$temp->execute();
$temp = $conn->prepare('SELECT company_id FROM tempId WHERE user_id = :user_id ');
$temp->bindParam(':user_id', $_SESSION['username'], PDO::PARAM_INT);
$temp->execute();
$tempResult= $temp->fetchAll(PDO::FETCH_ASSOC);
$company_id = $tempResult->company_id;
// $result[1] =$_SESSION('username');
} catch(PDOException $e) {
$result = $e->getMessage();
}
print json_encode($company_id);
Here:
$tempResult= $temp->fetchAll(PDO::FETCH_ASSOC);
If the fetchAll is successful, then $tempResult will be an array. For debugging, we can verify this using the convenient var_dump, e.g.
var_dump($tempResult);
If $tempResult is an array, I'm wondering about this expression:
$tempResult->company_id
What does that return? What do you expect that to return? Why?
EDIT: I know better than to answer a question with a question, or three questions.
However, I can't (in good conscience) bring myself to giving an "answer" to the problem with OP code...
at least not without (figuratively) scratching my head wondering about the actual SQL being used in the code.
What is the purpose of the TEMPORARY TABLE? Why is there an INSERT to it? Why is the UNSIGNED BIGINT datatype (returned by UUID_SHORT() function) being cast to a VARCHAR(17)? Is there some reason we want to lop off 1 or 2 digits when the function returns 18 or 19 decimal digits?
If the intent of this block of code is to return a value from MySQL UUID_SHORT() function, I'm not understanding why we need more than one statement. Obviously, there's something I'm missing, why this wouldn't suffice:
try {
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $db->id, $db->pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare('SELECT UUID_SHORT() AS company_id');
$sth->execute();
$company_id = $sth->fetchColumn();
} catch(PDOException $e) {
//var_dump($e->getMessage);
} finally {
if(isset($sth)){ $sth->close(); }
if(isset($conn)){ $conn->close(); }
}
(An application wouldn't churn database connections like this; there would either be a connection pool, or the connection would be passed in to this routine.)
Not sure, but as soon as fetchAll returns array, your code:
$company_id = $tempResult->company_id;
is invalid, you should:
$company_id = $tempResult[0]['company_id'];
or
$tempResult= $temp->fetch(PDO::FETCH_ASSOC);
$company_id = $tempResult['company_id'];