Problem is that if I update all users at one time the points row updates. But if I updating it by username row wont updating. I don't know why.
foreach($points as $p) {
$p = $p['points'] - $bet;
$username = $_SESSION['username'];
$q = $pdo -> prepare("UPDATE users SET points = '$p', username = '$username' ");
$q->execute();
}
without 'username = $username' all users updates perfectly.
Try:
try {
$q = $pdo->prepare("UPDATE users SET points = ? WHERE username = ?");
$q->execute(array($p, $username));
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Or:
try {
$q = $pdo->prepare("UPDATE users SET points = :p WHERE username = :username");
$q->bindParam(':p', $p);
$q->bindParam(':username', $username);
$q->execute();
} catch(Exception $e) {
echo $e->getMessage();
die();
}
I haven't tested it, but I think that should work.
Check out the site.
WHERE username = 'username' or else with that lack of code, all rows are getting updated and that could be either planned or disaster.
As points is an integer, you should NOT use quotes around the variable, as it will be interpreted as a string, thus failing. So the correct syntax would be:
"UPDATE users SET points = {$p}, username = '{$username}'"
Related
I'm making a function that i have to check if a userid is in this table already: if not he has to get into another page yet. But for some reason I get "NULL" back instead of the number of the userID.
my class:
public function countHobbies($userID){
try{
$conn = Db::getConnection();
$statement = $conn->prepare("select * from hobby where userID = '".$userID."'");
$userID = $this->getUserID();
$statement->execute();
$aantal = $statement->fetchAll(PDO::FETCH_ASSOC); //
$aantal->execute();
}
catch(throwable $e){
$error = "Something went wrong";
}
}
and this is on my html page:
$userArray = $_SESSION['user_id'];
$userID = implode(" ", $userArray);
$hobby = new Hobby();
$count = $hobby->countHobbies($userID);
if($count == false){
echo "no";
//header('Location: hobby.php');
}
else{
echo "yes";
}
There are at least two things you need to fix:
Always use parameter binding on the SQL statement. It may not be a security problem in this particular instance, but do get into the habit of using prepared statements. Because otherwise you'll find yourself in situations where you should've but didn't. https://www.php.net/manual/en/security.database.sql-injection.php
The $userID variable must be assigned before it is used.
In the end, it could look like this:
$userID = $this->getUserID();
$statement = $conn->prepare("select * from hobby where userID = ?");
$statement->bind_param("s", $userID);
I have problem without any error in my code that update row ..
if(!isset($error)){
try {
$sql = "UPDATE `invoice` SET `client`='".$client."', `company`='".$company."' , `clientemail`='".$clientemail."' , `mobailclient`='".$mobailclient."' , `startdate`='".$startdate."' , `enddate`='".$enddate."' WHERE `id` ='".$id."'";
$count = $db->exec($sql);
//redirect to invoice page
header('Location: invoice.php');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
This is my code , i try to get variable $sql and go to mysql phpmyadmin and its work good ,, but in file not work and i dont get any error
==== Update ====
i try this and not work
try {
$sql = 'UPDATE invoice SET client = :client, company = :company, clientemail = :clientemail, mobailclient = :mobailclient, startdate = :startdate, enddate = :enddate WHERE id = :id';
$statement = $db->prepare($sql);
$statement->bindParam(":client", $client);
$statement->bindParam(":company", $company);
$statement->bindParam(":clientemail", $clientemail);
$statement->bindParam(":mobailclient", $mobailclient);
$statement->bindParam(":startdate", $startdate);
$statement->bindParam(":enddate", $enddate);
$statement->bindParam(":id", intval($_GET['id']) );
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "<script>alert('".$statement->rowCount()."')</script>";
}
else
{
echo "<script>alert('No record updated')</script>";
}
Your query is opened for SQL Injection. You should use parameterized query which provide a kind of protection against SQL injection but will not provide 100% of protection. Kindly visit this Post for more details.
Try the following code by replacing table and column names.
$client = "my name";
$company = "my-company";
$id= 2;//make sure your table has a record with that specific id
$sql = 'UPDATE invoice SET client = :client, company = :company WHERE id = :id'; // here i am updating only two columns
//You can add more column that you want to upate like ColumnName = :ParameterIdentifier
//Where ParameterIdentifier Is the name of parameter used in bindParam as in my example company
$statement = $db->prepare($sql);
$statement->bindParam("client", $client); //Binding parameter for client
$statement->bindParam("company", $company); //Binding parameter for company
$statement->bindParam("id", $id);
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "Record updated successfully";
}
else
{
echo "No record updated";
}
I have three queries on my login script. One select query checks the users' credentials, another to update the last login, and the third one is a select query to see whether the user exists in another table, so if the user exists in the table, go some where. If the user doesn't exist, go somewhere else.
The third query is the one is acting weird. Below:
require_once '../includes/sessions.php';
//echo 'hello';
$employerlogindata = $_POST['employerlogindata'];
$data = json_decode($employerlogindata);
$employeremailfromjs = $data->employeremail;
$employerpasswordfromjs = $data->employerpassword;
//sanitization
$employeremail = htmlentities($employeremailfromjs);
$employerpassword = htmlentities($employerpasswordfromjs);
//PHP validation rules
$validflag = true;
function checkblanks($variable){
if($variable == ''){
$validflag = false;
print_r('Empty Inputs. Please try again.');
}else {
$variable = trim($variable);
$variable = stripslashes($variable);
return $variable;
}
}
checkblanks($employeremail);
checkblanks($employerpassword);
if($validflag == false) {
echo 'You have problematic entries. Try again.';
} else {
try{
$sql = "SELECT EID AS dbeid, EMPLOYER_EMAIL AS dbemail, `PASSWORD` AS dbpwd, EMPLOYER_NAME AS dbcompanyname, LAST_LOGIN AS dblastlogin FROM userpwd WHERE EMPLOYER_EMAIL = :employeremail;";
$query = $conn->prepare($sql);
$query->bindParam(":employeremail", $employeremail);
$query->execute();
//echo "select statement successfully executed";
//echo $sql;
} catch(PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
//echo $query->rowCount();
if ($query->rowCount() == 0){
echo "Email/Password combo was not found in the system.";
}else {
$result = $query->fetch(PDO::FETCH_OBJ);
//print_r($result);
$dbeid = $result->dbeid;
$dbemail = $result->dbemail;
$dbpwd = $result->dbpwd;
$dbcompanyname = $result->dbcompanyname;
$dblastlogin = $result->dblastlogin;
//echo $dbeid;
if(password_verify($employerpassword, $dbpwd)){
try{
$sql = "UPDATE userpwd SET LAST_LOGIN = NOW() WHERE EMPLOYER_EMAIL = :employeremail; ";
$query = $conn->prepare($sql);
$query->bindParam(":employeremail", $employeremail);
$query->execute();
}catch (PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
$_SESSION['EID'] = $dbeid;
$_SESSION['EMPLOYER_EMAIL'] = $dbemail;
$_SESSION['EMPLOYER_NAME'] = $dbcompanyname;
$_SESSION['LAST_LOGIN'] = $dblastlogin;
//echo "Logged in";
} else {
echo "Email/Password combination is invalid. Please Try Again.";
}
try{
$select = "SELECT EID from e_profile WHERE EID=:eid";
$stmt = $conn->prepare($select);
$stmt->bindParam(":eid", $sessemployerid);
$stmt->execute();
}catch(PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
$res = $stmt->fetch();
$eid = $res['EID'];
$count = $stmt->rowCount();
if($stmt->rowCount() == 1){
echo "employerdashboard.php $eid $count";
$stmt->closeCursor();
} else if ($stmt->rowCount() == 0){
echo "e_profile.php $eid $count";
$stmt->closeCursor();
}
}
}
?>
After a set of login credential is successful, the script hits both the second and the third queries. However, the third query takes on the results of the previous ran query. After a second click on the frontend with the same credentials, it produces the right results.
I thought maybe I could find the functionality of mysqli_free_result() in PDO's closeCursor, but that doesn't work. I want it to produce the right result the first time.
Any clues as to why this is happening?
Your variable is out of date (or at least that is my theory), as I said in the comments.
If you have
global $sessemployerid = $_SESSION['EID'];
Then you do
$_SESSION['EID'] = $dbeid;
Then you use $sessemployerid it will not be equal to $_SESSION['EID'] = $dbeid. It will be equal to the previous value of the session when it was assigned, which may or may not be correct. Probably on the first attempt it is wrong, then on subsequent attempts it is correct.
Just to lay it out a bit further:
//you assign $sessemployerid way up here
global $sessemployerid = $_SESSION['EID'];
...
//then you update the session
if(password_verify($employerpassword, $dbpwd)){
try{
$sql = "UPDATE userpwd SET LAST_LOGIN = NOW() WHERE EMPLOYER_EMAIL = :employeremail; ";
$query = $conn->prepare($sql);
$query->bindParam(":employeremail", $employeremail);
$query->execute();
}catch (PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
$_SESSION['EID'] = $dbeid; //<--- here you update the session but neglect $sessemployerid
$_SESSION['EMPLOYER_EMAIL'] = $dbemail;
$_SESSION['EMPLOYER_NAME'] = $dbcompanyname;
$_SESSION['LAST_LOGIN'] = $dblastlogin;
//echo "Logged in";
} else {
....
//then you use $sessemployerid, but it has a stale value (sometimes)
$select = "SELECT EID from e_profile WHERE EID=:eid";
$stmt = $conn->prepare($select);
$stmt->bindParam(":eid", $sessemployerid);
To fix this you could use a reference assignment
global $sessemployerid =& $_SESSION['EID'];
This can be demonstrated by this simple code:
$a = 1;
$b =& $a; //initial assignment, with reference
echo $b."\n";
$a = 2; //change the value of $a
echo $b; //$b is auto-magically updated
See it here
Ouputs
1
2
If you do it this way (the "normal" way)
$a = 1;
$b = $a; //initial assignment, normal
echo $b."\n";
$a = 2; //change the value of $a
echo $b; //$b is not updated
The output is
1
1
Alternatively you could simply update the global after changing the session's value:
if(password_verify($employerpassword, $dbpwd)){
...
$_SESSION['LAST_LOGIN'] = $dblastlogin;
global $sessemployerid = $_SESSION['EID'];
}else{
...
Because the value of $sessemployerid is out of sync with $_SESSION['EID'] you will get inconstant behavior depending on if you had updated the session or not on a previous page attempt.
Hope that makes sense.
So I am grabbing the amount of rows in a specific table where the username is already in the database like so:
$second_sql = $db->prepare("SELECT * FROM users WHERE username = :username");
$second_sql->bindParam(':username', $username);
$second_sql->execute();
if($second_sql->rowCount() == 1) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
The problem is it's not working. If you need more of the script just tell me.
Some databases does not report the row count with PDO->rowCount() method.
SQLite, for instance.
So don't use rowCount(); doing so makes your code less portable.
Instead use the COUNT(*) function in your query, and store the result in a variable.
Finally, use that variable to fetch the one and only column (users) using the fetchColumn() method.
So you can play with this:
try {
$second_sql = $db->prepare("SELECT COUNT(*) from users WHERE username = :username");
$second_sql->bindParam(':username', $username, PDO::PARAM_STR);
$second_sql->execute();
$count = $second_sql->fetchColumn();
} catch (PDOException $e) {
// Here you can log your error
// or send an email
// Never echo this exception on production
// Only on development fase
echo "Error: " . $e->getMessage();
}
if ($count) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
Perhaps you wanna test you condition for a single row:
if ($count == 1)
Hope this helps you.
Cheers!
I'm trying to fetch results using mysqli->fetch_row() (or fetch_object(), fetch_array()), yet when I go to run the code at run time it gives me the following error:
Fatal error: Call to a member function fetch_row() on a non-object in...on line 23.
The var in question that does this is $results in the code below. $user and $password gain their values from another .php file that this file is being included in so that's not really important at the moment. Now correct me if I'm wrong but if $results is being set = to $db->query($query) then isn't it supposed to inherit the properties of $db aka the mysqli class?
class mySQLHelper{
public function checkPass($user, $pass){
global $db;
$db = new mysqli();
$db->connect('localhost', 'root', '', 'mydb');
if (mysqli_connect_errno()){
echo 'Can not connect to database';
echo mysqli_connect_errno(). mysqli_connect_error();
exit;
return false;
}
$query = "SELECT user, password FROM Users WHERE user = $user AND password = $pass " ;
echo $query;
$results = $db->query($query);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
$results->close();
$url = 'http://'. $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
if(!$results){
// mysqli_close($db);
// header("Location:.$url.login.php&msg=1");
}
else{
// mysqli_close($db);
// header("Location:.$url.featured.php");
}
}
}
Your query is failing on this line:
$results = $db->query($query);
Because of this, $results is false - not a result object as you expect.
To fix the issue, you need to add quotes around your variables (or use prepared statements):
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
I would suggest updating to use a prepared statement to prevent SQL-injection issues too though:
$stmt = $db->prepare('SELECT user, password FROM Users WHERE user = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$results = $stmt->get_result();
You script is lacking error checking, and therefore the error in the query is not handled.
$query = "SELECT user, password FROM Users
WHERE user = '$user' AND password = '$pass' " ;
// ^ quotes needed
echo $query;
$results = $db->query($query);
// handle a error in the query
if(!$results)
die($db->error);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
If you user & password field text or varchar, then you need to use single quote around them
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
You have to check, if query runs properly:
if ($result = $mysqli->query($query))
{
}
Use: var_dump($results) to check what it contains
Why are you checking if($results) after trying to manipulate it?
This...
$results->close();
//...
if(!$results){
//...
}
Should be...
if(!$results){
//...
}
$results->close();