IF and ELSE statement not working - php

I am trying to award a user a badge if their points are 10,000. There is a field in the table called badge1 with a default value set to locked and a points row. I am running and if statement that if the users points are 10,000 then UPDATE the badge1 row from locked to unlocked. My code seems correct but It is neither updating the the field nor showing any errors.
<?php
$db = new PDO('mysql:host=hostname;dbname=databasename;charset=UTF-8', 'username', 'password');
$username = $_SESSION['username'];
$q = "SELECT Points FROM login_users WHERE username ='$username'");
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
if($Points == "10000") {
$awardBadge = $db->exec("UPDATE login_users SET badge1=unlocked WHERE username=?");
$Points->execute(array($username))
} else {
print "";
}
?>
UPDATE:
I managed to get it working.. however the problem is I am a bit new to converting old sql to PDO so this is not very secure but this is what works:
<?php
$connect = mysql_connect("host","username","password");
mysql_select_db("databasename");
$username = $_SESSION['jigowatt']['username'];
$q = "SELECT Points FROM login_users WHERE username = ('$username')";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
?>
// Place somewhere
<?php
if($Points >= "10000") {
$result = mysql_query("UPDATE login_users SET maneki='unlocked' WHERE username='$username'");
} else {
print "Badge has not been unlocked";
}
?>

"10000" string should be an 10000 int
And also, you might want to make a choice here too. You're using 2 types of setting up a mysql-database connection. the old-fashioned mysql_function() way and the new fancy PDO method.
I think working with the PDO version is safer, since newer PHP versions will not support the old methods anymore... That... and it just looks dirty ;P
Try this:
<?php
session_start();
$dbSession = new PDO('mysql:host=***;dbname=***', '***', '***');
$selectQuery = $dbSession->prepare('
SELECT `User`.`Points`
FROM `login_users` AS `User`
WHERE `User`.`username` = :username
');
$selectQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$user = $selectQuery->fetch(PDO::FETCH_ASSOC);
if ( !empty($user) && $user['Points'] == 10000 ) {
$updateQuery = $dbSession->prepare('
UPDATE `login_users`
SET `badge1` = \'unlocked\'
WHERE `username` = :username');
$updateQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$updateQuery->execute();
}
?>
Usefull resources:
PHP Database Objects (PDO)
PHP Sessions
MySQL Datamanipulation
MySQL SELECT syntax
MySQL UPDATE syntax

Better check if >= 10000 and not yet awarded. That could you also be done in SQL so you don't need that logic in PHP.
UPDATE login_users SET badge1=unlocked WHERE points >= 10000 and badget1 <> unlocked

The issue is caused by $point value which actually is not equal to 10000, but is NULL.
So I propose to always use var_dump() to get the actual value of the variable in such cases.

one tip: check the PDO docs, before you write php code! You use PDO and mysql commands on same time for same job!?? why???

Try this if($Points == 10000) instead of if($Points == "10000")
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.

if($Points==10000){
$awardBadge = $db->prepare("UPDATE login_users SET badge1=unlocked WHERE username=?");
$awardBadge->execute(array($username));
}

Related

Can't find the error in my SQL syntax - PHP (check manual for syntax?)

The Problem:
I am trying to subtract 0.05 from the variable cash_amount in my database called users, and i am calling this file by ajax but nothing is occurring. To fix this, i opened the file in my browser and i got this error:
The Error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
The Code:
PHP:
<?php
session_start();
$servername = "localhost";
$username = "myUser";
$password = "myPass";
$dbname = "myDBname";
$cash_amount = $_SESSION['cash_amount'];
// Create connection
$userid = $_SESSION['id'];
// You must enter the user's id here. /\
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$_SESSION['cash_amount'] -= 0.05;
$newAmount = $cash_amount - 0.05;
$sql = "UPDATE users SET cash_amount = $newAmount WHERE id = $userid";
$result = $conn->query($sql);
if($result)
{
echo "5 cents have been subtracted!";
}
else
{
echo mysqli_error($conn);
session_start();
session_unset();
session_destroy();
}
$conn->close();
?>
Javascript/AJAX:
function countdownEnded() {
//make serverscreen dissapear
document.getElementById('serverScreenWrapper').style.display = 'none';
document.getElementById('serverScreenWrapper').style.opacity = '0';
document.getElementById("cashOutNumTwo").style.right = '150%';
document.getElementById("cashOutNumOne").style.right = '150%';
//start Timer
setInterval(gameTimer.update, 1000);
//make player move again
socket.emit('4');
socket.emit('6');
//make game appear
document.getElementById('gameAreaWrapper').style.opacity = 1;
//play sound
document.getElementById('spawn_cell').play();
//cut 5 cents from account - php function
$.ajax({
type: "POST",
url: 'http://cashballz.net/game/5game/subtract5.php',
data: { },
success: function (data) {
alert(data);
}
});
}
My Database:
My table is called users and its inside of the DB casball_accounts.
Here is the format:
id | first_name | last_name | email | password | cash_amount | 4 in between | hash | active
Conclusion:
I am pretty confused on why my php code isn't working, I have already tried searching for a fix and i found the words "SQL Injection" but I still didn't find the error. I am advanced at JS but a beginner to PHP, so please bear with me. Thanks!
You could simplify the query and do
$sql = "UPDATE users SET cash_amount = cash_amount - 0.05 WHERE id = $userid";
But to avoid the possibility of SQL Injection I would suggets also changing the code to use a parameterised and bound query like this
$sql = "UPDATE users SET cash_amount = cash_amount - 0.05 WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
You're interpolating data into the query, which, if that is what you want, you go with Mostafa's answer and put quotes around those values in case they're malformed. Which also means you have to check to see if they're legitimate values before putting them into the query.
However, they may also be subject to user input somewhere up the line, so do use PDO's prepared statements.
$sql = "UPDATE users SET cash_amount = :newAmount WHERE id = :userid";
$conn = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
$conn->execute([':newAmount' => $newAmount, ':userid' => $userid])
...should take care of the issue. But making sure you have what tyou think you have can prevent a lot of red herrings.
The syntax error complains there's a problem near '' which means there is nothing following the point where it gets confused. I.e., it gets confused at the end of the query.
If $userid is blank, your SQL query will be
UPDATE users SET cash_amount = ... WHERE id =
This is clearly wrong syntax, because = requires two operands.
You need to make sure your $userid has a non-blank value.
The suggestions in other answers try to work around the issue by using quotes or query parameters, but the real problem is that you don't check that $userid has a value before you use it.
Replace
$sql = "UPDATE users SET cash_amount = '$newAmount' WHERE id = '$userid'";
instead
$sql = "UPDATE users SET cash_amount = $newAmount WHERE id = $userid";

call to undefined function execute()

bellow is my code.Error shown is like
fatal error: call to undefined function execute() on line 21,
how could i solve this problem?
<?php
include 'config/dbconfig.php';
include 'lib/function.php';
include 'helper/helper.php';
$db = new rootfunc();
$fm = new formate();
if(!empty($_POST['name']) or !empty($_POST['email']) or !empty($_POST['password1']) or !empty($_POST['dob']) or !empty($_POST['gender']) ){
$name = $fm->validation($_POST['name']);
$email = $fm->validation($_POST['email']);
$password = $fm->validation($_POST['password1']);
$dob = $_POST['dob'];
$gender = $fm->validation($_POST['gender']);
$query = $pdo->prepare("SELECT * FROM user_table WHERE name = ? AND email = ?");
$query = execute(array($name,$email));
$numRow = $query->rowCount();
if(!$numRow){
$query = "INSERT INTO user_table (name,email,password,dob,gender) VALUES (?,?,?,?,?)";
$query = $pdo->prepare($query);
$query->execute(array($name,$email,$password,$dob,$gender));
echo "Congrates, please login..";
}else{
echo "name and email exist..";
}
}
?>
In both cases you are overwriting $query:
$query = "INSERT INTO user_table (name,email,password,dob,gender) VALUES (?,?,?,?,?)";
$query = $pdo->prepare($query);
You need to give the execution a different variable to hold the object, for example:
$query = "INSERT INTO user_table (name,email,password,dob,gender) VALUES (?,?,?,?,?)";
$result = $pdo->prepare($query);
$result->execute(array($name,$email,$password,$dob,$gender));
In addition you should allow users to use the passwords / phrases they desire. Don't limit passwords.
While you're working with passwords never store them as plain text! Please use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. Make sure that you don't escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.
I also noticed this in your code
$numRow = $query->rowCount();
Since the query is a SELECT query it will not work with rowCount()
From the docs:
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
For SELECT when you are not doing a COUNT() query you can return the number of rows like this after you execute the query;
$rows = $result->fetchAll();
$num_rows = count($rows);
In your case it is not necessary to check the count though - just check to make sure the query executed which is enough to get into your conditional statements.

How to check if a row exists compared to another value

I am not sure how to go about this in PHP & MySQL;
But basically, I just want to check to see if a row exists in a table, and if it does, return a error, example:
$exists = MYSQL CODE TO CHECK HOW MANY ROWS INCLUDE BADGE_ID
if($exists >= 1)
{
$errors[] = "Exists.";
}
Something like that, because I'm coding a small shop script and I want it to check to make sure that they don't already have the badge_id. Structure of the db is user_id and badge_id (user_id = 1, badge_id = 1; for an example)
//Mysql
$res = mysql_query("YOUR QUERY");
if(mysql_num_rows($res) > 0) {
$errors[] = "Exists.";
}
//PDO
$query = $db->prepare("YOUR QUERY");
$ret = $query->execute();
if($ret && $query->rowCount() > 0) {
$errors[] = "Exists.";
}
for this query as
$query=mysql_query("SELECT * from table WHERE userid = 1 AND badgeid = 1");
and in php
if(mysql_num_rows($query)>0){
// whatever you want if match found
}else{
echo "No match Found".
}
$sql = "SELECT COUNT(*) FROM `table_name` WHERE `user_id` = '1' AND `badge_id` = '1' "
$exists = mysql_query($sql) ;
if(mysql_num_rows($exists) >= 1) {
$errors[] = "Exists.";
}else {
// doesn't exists.
}
Try using PDO instead of the old mysql_query() functions for they are deprecated since PHP 5.5.
For a simple query:
$slcBadge = $con->query('SELECT badge_id FROM badges');
if ($slcBadge->rowCount() > 0) {
$errors[] = 'Exists.';
}
Or if you want to fetch all rows from a single user:
$sqlBadge = 'SELECT id_badge FROM badges WHERE id_user = :idUser';
$slcBadge = $con->prepare($sqlBadge);
$slcBadge->bindParam(':idUser', $idUser, PDO::PARAM_INT);
$slcBadge->execute();
if ($slcBadge->rowCount() > 0) {
$errors[] = 'Exists.';
}
Notice that in the second piece of code I used prepare() and execute() rather than query(). This is to protect you query from SQL injection. By using prepare() you fix the construct of your query so if a user enters a query string as a value, it will not be executed. You only need to prepare a query if a user can enter a value which will be used in your query, otherwise query() will do just fine. Check out the injection link for more detailed info.
Your version of PHP is important:
mysql_* functions are deprecated as of 5.4, and
Removed as of 5.5
It is advised to either implement PDO or Mysqli
mysql:
This extension is now deprecated, and deprecation warnings will be generated when connections are established to databases via mysql_connect(), mysql_pconnect(), or through implicit connection: use MySQLi or PDO_MySQL instead
Dropped support for LOAD DATA LOCAL INFILE handlers when using libmysql. Known for stability problems
Added support for SHA256 authentication available with MySQL 5.6.6+
For reference please see the changelog
Structuring your Query
First of all I'm assuming you are indexing your fields correctly refer to this article I posted on Stack Exchange.
Second of all you need to consider efficiency depending on the volume of this table: doing a SELECT * is bad practice when you only need to count the records - mysql will cache row counts and make your SELECT Count(*) much faster. with indexes this is furthermore efficient.
I would simply consider something along the line of this:
$dsn = 'mysql:host=127.0.0.1;dbname=DATABASE';
$db = new PDO($dsn, 'username', 'password', array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
));
NOTE:
where host=127.0.0.1 if your user has been granted access via localhost then you need this to state localhost - or grant the user privileges to 127.0.0.1
NOTE:
with SET NAMES there is also a bug with the PDO driver from 5.3 (I believe) whereby an attacker can inject nullbytes and backspace bytes to remove slashing to then inject the query.
Quick example:
// WARNING: you still need to correctly sanitize your user input!
$query = $db->prepare('SELECT COUNT(*) FROM table WHERE user_id = ? AND badge_id = ?');
$query->execute(array((int) $userId, (int) $badgeId));
$total = $query->fetchAll();
$result = mysql_query("SELECT COUNT(*) FROM table WHERE userid = 1 AND badgeid = 1 LIMIT 1") or die(mysql_error());
if (mysql_result($result, 0) > 0)
{
echo 'exist';
}
else
{
echo 'no';
}

PHP and MySQL Select a Single Value [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I'd like to know how to select a single value from my MySQL table. The table includes columns username and id amongst others (id is auto-increment and username is unique). Given the username, I want to set a session variable $_SESSION['myid'] equal to the value in the id column that corresponds to the given username. Here's the code that I've already tried:
session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
$_SESSION['myid'] = $value;
So far I'm getting:
Catchable fatal error: Object of class stdClass could not be converted to string.
Casting $value to type string does not fix the problem.
Don't use quotation in a field name or table name inside the query.
After fetching an object you need to access object attributes/properties (in your case id) by attributes/properties name.
One note: please use mysqli_* or PDO since mysql_* deprecated. Here it is using mysqli:
session_start();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'username', 'password', 'db_name');
$link->set_charset('utf8mb4'); // always set the charset
$name = $_GET["username"];
$stmt = $link->prepare("SELECT id FROM Users WHERE username=? limit 1");
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$value = $result->fetch_object();
$_SESSION['myid'] = $value->id;
Bonus tips: Use limit 1 for this type of scenario, it will save execution time :)
The mysql_* functions are deprecated and unsafe. The code in your question in vulnerable to injection attacks. It is highly recommended that you use the PDO extension instead, like so:
session_start();
$query = "SELECT 'id' FROM Users WHERE username = :name LIMIT 1";
$statement = $PDO->prepare($query);
$params = array(
'name' => $_GET["username"]
);
$statement->execute($params);
$user_data = $statement->fetch();
$_SESSION['myid'] = $user_data['id'];
Where $PDO is your PDO object variable. See https://www.php.net/pdo_mysql for more information about PHP and PDO.
For extra help:
Here's a jumpstart on how to connect to your database using PDO:
$database_username = "YOUR_USERNAME";
$database_password = "YOUR_PASSWORD";
$database_info = "mysql:host=localhost;dbname=YOUR_DATABASE_NAME";
try
{
$PDO = new PDO($database_info, $database_username, $database_password);
}
catch(PDOException $e)
{
// Handle error here
}
You do this by using mysqli_fetch_field method.
session_start();
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' limit 1";
$result = mysqli_query($link, $sql);
if ($result !== false) {
$value = mysqli_fetch_field($result);
$_SESSION['myid'] = $value;
}
Note: you can do that by using mysql_fetch_field() method as well, but it will be deprecated in php v5.5
mysql_* extension has been deprecated in 2013 and removed completely from PHP in 2018. You have two alternatives PDO or MySQLi.
PDO
The simpler option is PDO which has a neat helper function fetchColumn():
$stmt = $pdo->prepare("SELECT id FROM Users WHERE username=?");
$stmt->execute([ $_GET["username"] ]);
$value = $stmt->fetchColumn();
Proper PDO tutorial
MySQLi
You can do the same with MySQLi, but it is more complicated:
$stmt = $mysqliConn->prepare('SELECT id FROM Users WHERE username=?');
$stmt->bind_param("s", $_GET["username"]);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
$value = $data ? $data['id'] : null;
fetch_assoc() could return NULL if there are no rows returned from the DB, which is why I check with ternary if there was any data returned.
Since PHP 8.1 you can also use fetch_column()
$stmt->execute();
$value = $stmt->get_result()->fetch_column();
Try this
$value = mysql_result($result, 0);
When you use mysql_fetch_object, you get an object (of class stdClass) with all fields for the row inside of it.
Use mysql_fetch_field instead of mysql_fetch_object, that will give you the first field of the result set (id in your case). The docs are here
It is quite evident that there is only a single id corresponding to a single username because username is unique.
But the actual problem lies in the query itself-
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
O/P
+----+
| id |
+----+
| id |
+----+
i.e. 'id' actually is treated as a string not as the id attribute.
Correct synatx:
$sql = "SELECT `id` FROM Users WHERE username='$name'";
i.e. use grave accent(`) instead of single quote(').
or
$sql = "SELECT id FROM Users WHERE username='$name'";
Complete code
session_start();
$name = $_GET["username"];
$sql = "SELECT `id` FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result)
$value = $row[0];
$_SESSION['myid'] = $value;
try this
session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' LIMIT 1 ";
$result = mysql_query($sql) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
$_SESSION['myid'] = $row['id'];
}

echo data from database PDO

Trying to echo out in this case the users username. I've had a friend help me, but he seems like he can't solve it either. So I'm asking you guys.
Basically, I'm right now trying to take the username from the person who logged in. The sessions which get set when you log in is called "user_id". Never mind, this is my code`
$user = $dbh->prepare("SELECT `username` FROM `users` WHERE `user_id` = ':user_id'");
$user->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_STR);
$user->execute();
while($row = $user->fetch(PDO::FETCH_NUM)){
$user_name = $row['1'];
}
?>
<h3>Welcome <p class="blue"><?php echo $user_name;?></p></h3><br/>`
With this, I get this error:
Undefined variable: user_name in
i know this is wrong, since it obviously doesn't work. But I've also tried setting sessions at that place in the while loop like this.
$_SESSION['user_id'] = $row['username'];
but then I get a blank result. Which means that there's no value of the session, or am I wrong?
You don't need quotes in the $row variable
while($row = $user->fetch(PDO::FETCH_NUM)){
$user_name = $row[0];
}
In your original code, its $row['1']. You don't have a field called 1 so remove the single quotes from around it.
Also, rows (when numerically indexed) start at 0, so the username field would be $row[0]
EDIT
And to touch on what #jeroen mentioned, in your SQL query, you shouldn't have quotes around your parameterized values:
$user = $dbh->prepare("SELECT `username` FROM `users` WHERE `user_id` = :user_id");
When there is no data returned, while won't be executed even once.
So, check your query.
To start you never checked if the user actually exists in the database, so what I personally would do is prepare the query and set a value to the default username- run the query and if no rows are returned then do nothing, if we actually have a row then fetch the corresponding column value in that row ('username') and set the variable to that.
$user = $dbh->prepare("SELECT `username` FROM `users` WHERE `user_id` = ':user_id'");
$user->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_STR);
$user->execute();
$UserName = "Unknown!";
while( $row = $user->fetch(PDO::FETCH_NUM) ){
$UserName = $row['username'];
}
echo '<h3>Welcome <p class="blue">{$UserName}</p></h3><br/>';

Categories