Not sure if this is even possible, I am trying to get it to where "ItemA" has a value of 100 in the database. Which I have assigned a value to problem, what I really want is if a user inputs 50 into an input field, that "ItemA" value will now show 150 when it is called back in a select query. I am unsure of how to add the value in a column and a users input together.
I am new to PHP and SQL, so please forgive me. Any help is greatly appreciated and I thank you for your time!
The PHP that I have:
<?
$payout = $_POST["payout"];
$payouts = $_GET["payout"];
$withdraw = $_POST["bank_withdraw"];
$cashspent = $_POST["cash_spent"];
$servername = "localhost";
$username = "*****";
$password = "*****";
$db = "*****";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error){
die("Connection failed: ". $conn->connect_error);
}
$sql = "UPDATE finances SET payout = '$payouts' + ? WHERE finance_id = 1";
$stmt = mysqli_stmt_init($conn);
if ( ! mysqli_stmt_prepare($stmt, $sql)){
die(mysqli_error($conn));
}
mysqli_stmt_bind_param($stmt, "ii",
$payout,
$payouts
);
mysqli_stmt_execute($stmt);
In this example, I am trying to have it where a user is able to add the two values from what is already in the database.
Item in database (payout) = 100
Input from user = 50
Item from database + input from user = 150, showing in database
if I understand your question correctly there are 2 parts:
Select payout from database and add it to the user input.
update the value in the database
For 1) select the payout from the database $select_sql = "SELECT payout FROM finances WHERE finance_id = 1"; and you could use a variable such as $increasedPayout and assign this new variable $increasedPayout = $payouts + $select_sql;
and then for 2) use the $increasedValue variable in your SQL UPDATE statement.
$sql = "UPDATE finances SET payout = '$increasedPayout' WHERE finance_id = 1";
Related
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";
I've written the below query:
At the moment this pulls back everything from the MarketingCampaigns table, regardless of which user created the record.
I need to be able to return the result, which counts only the records created by that user.
<?php
$servername = "localhost";
$username = "root";
$password = "doimkr943k3f";
$dbname = "crm4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT format(count(id),0) as id12 FROM MarketingCampaigns";
$result2 = $conn->query($sql);
$row = $result2->fetch_assoc();
echo $row["id12"];
?>
The below is a query I can see has been 'auto-generated' by the tool I use, which checks which fields the user should see in table view. I'm just really unsure how to convert this into the simple, single value SQL queries I have above.
// mm: build the query based on current member's permissions
$DisplayRecords = $_REQUEST['DisplayRecords'];
if(!in_array($DisplayRecords, array('user', 'group'))){ $DisplayRecords = 'all'; }
if($perm[2]==1 || ($perm[2]>1 && $DisplayRecords=='user' && !$_REQUEST['NoFilter_x'])){ // view owner only
$x->QueryFrom.=', membership_userrecords';
$x->QueryWhere="where `Complaints`.`id`=membership_userrecords.pkValue and membership_userrecords.tableName='Complaints' and lcase(membership_userrecords.memberID)='".getLoggedMemberID()."'";
}elseif($perm[2]==2 || ($perm[2]>2 && $DisplayRecords=='group' && !$_REQUEST['NoFilter_x'])){ // view group only
$x->QueryFrom.=', membership_userrecords';
$x->QueryWhere="where `Complaints`.`id`=membership_userrecords.pkValue and membership_userrecords.tableName='Complaints' and membership_userrecords.groupID='".getLoggedGroupID()."'";
}elseif($perm[2]==3){ // view all
// no further action
}elseif($perm[2]==0){ // view none
$x->QueryFields = array("Not enough permissions" => "NEP");
$x->QueryFrom = '`Complaints`';
$x->QueryWhere = '';
$x->DefaultSortField = '';
}
I have a table called membership_userrecords which includes the below fields.
You can see the PK value in the table and which user owns it.
I'm just not sure how to do the SQL query.
Can you help?
EDIT: I really need to work on my PHP syntax lol. Thanks #aynber
Assuming the username and the memberID are the same, this should be your query.
$sql= $conn->prepare("SELECT format(count(*),0) as id12 FROM MarketingCampaigns where memberID = ?");
$sql->bind_param("s", $username);
$sql->execute();
$sql->bind_result($row);
$sql->fetch();
echo $row;
I'm really unsure about your data here.
Hey I have an online database which needs to be populated with sensor values periodically. There are 7 variables(columns) coupled with a timestamp column to make each row of the table. Problem is these variables are pushed a few at a time with the rest as 0. Now I'm coding an algo which will only insert a row if all values of latest row (by timestamp) are filled completely(not 0), else it will update the latest row.
Here's my PHP code for one of the insert php files which inserts 3 variables at a time - temp, pressure and altitude.
<?php
// Prepare variables for database connection
$dbusername = "uxpertla_terr"; // enter database username, I used "arduino" in step 2.2
$dbpassword = "abc123"; // enter database password, I used "arduinotest" in step 2.2
$server = "localhost";
// Connect to your database
$dbconnect = mysqli_connect($server, $dbusername, $dbpassword);
// Prepare the SQL statement
$sdl = "SELECT * FROM uxpertla_test_db.testt ORDER BY time DESC LIMIT 1";
$snd=mysqli_query($sdl);
$row = mysqli_fetch_array($snd,MYSQLI_ASSOC);
if($row)
{
if($row['Temperature']==0||$row['Pressure']==0||$row['Humidity']==0||$row['Light']==0)
{
$sql = "UPDATE uxpertla_test_db.testt
SET temp='".$_GET["value"]."',
pressure='".$_GET["value2"]."',
altitude='".$_GET["value3"]."'
WHERE time=".strtotime($row['time'])."";
}
else
$sql = "INSERT INTO uxpertla_test_db.testt
(temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";
}
else
$sql = "INSERT INTO uxpertla_test_db.testt
(temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";
// Execute SQL statement
mysqli_query($sql);
?>
Sorry if the code's not pretty, but I need help with the where clause of update query in the second if block..
Figured out the answer.. :p
<?php
// Prepare variables for database connection
$dbusername = "uxpertla_terr"; // enter database username, I used "arduino" in step 2.2
$dbpassword = "abc123"; // enter database password, I used "arduinotest" in step 2.2
$server = "localhost";
// Connect to your database
$dbconnect = mysqli_connect($server, $dbusername, $dbpassword);
$sdl = "SELECT * FROM uxpertla_test_db.testt ORDER BY time DESC LIMIT 1";
$snd=mysqli_query($dbconnect,$sdl);
$row = mysqli_fetch_array($snd,MYSQLI_ASSOC);
if($row['Temperature']==0||$row['Pressure']==0||$row['Humidity']==0||$row['Light']==0)
{
$sql = "UPDATE uxpertla_test_db.testt
SET temp='".$_GET["value"]."',
pressure='".$_GET["value2"]."',
altitude='".$_GET["value3"]."'
ORDER BY time DESC LIMIT 1";
}
else
$sql = "INSERT INTO uxpertla_test_db.testt
(temp,pressure,altitude) VALUES('".$_GET["value"]."', '".$_GET["value2"]."','".$_GET["value3"]."')";
// Execute SQL statement
mysqli_query($dbconnect,$sql);
?>
So im fairly new to coding, and have just started on a project for fun.
I try to build a RPG game, and i have got to the point where players can fight and take damage. So i want to add a passive health regeneration.
So i was thinking that i would use a conjob to request a php file every 10min and update all players HP with +10.
What i have got with my very poor MySQL knowlege is;
<?php
/*
* hp_reg.php, auto updater +10hp to players.
*/
//DATABAS CONNECTION
$dbserver="my";
$dbusername ="db";
$dbpassword ="conection";
$db ="information";
//CREATE CONNECTION
$conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
$query = "SELECT health FROM users";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($query);
$newhp = $result + 10;
$sql = "INSERT INTO users(health) VALUES ($newhp)";
Wich clearly will not work at all!
Any tips on what to change in order to get it to work?
All pointers are much appreciated.
$sql = "UPDATE users SET health = health + 10";
Updated Code
<?php
/*
* hp_reg.php, auto updater +10hp to players.
*/
//DATABAS CONNECTION
$dbserver="my";
$dbusername ="db";
$dbpassword ="conection";
$db ="information";
//CREATE CONNECTION
$conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
$sql = "UPDATE users SET health = health + 10";
$result = mysqli_query($conn, $sql);
To increase the health column of all users by 10, you can execute the following query:
UPDATE users SET health = health + 10
Assuming:
you want update health of One user;
each user have an unique id;
the unique id is stored in your database as userID (if not, change it with your correct field name);
you have to try in this way:
$query = "SELECT health FROM users WHERE userID='$userID'";
$result = mysqli_query( $conn, $query );
$row = mysqli_fetch_assoc( $query );
$newhp = $row['health'] + 10;
$query = "UPDATE users SET health='$newhp' WHERE userID='$userID'";
$result = mysqli_query( $conn, $query );
At last, take a look to how preventSQL-injection in PHP and how check if your result is empty
I am new in PHP. I use session first time. I have two tables in db. First table with name pacra_teams with column id and title. Second table is og_users with multiple column but i use team_title as foreign key as store id against team title.
Now i want to create a session and want to display team name from table pacra_teams and user name from table og_users.
I try following code but i failed.
<?php
// starts session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
LIMIT 1
";
// setting variable values during session
$_SESSION['og_users.username']=$username;
$_SESSION['pacra_teams.title']=$title;
?>
call these variables
<?php
session_start();
?>
<?php
print_r($_SESSION);
?>
Please help me how i can do this?
One Thing More. if i run seesion.php page it display undefine variable "title"
and if i run print code. It display username "root" but i dont have any user name root in my db
You already defined a query but didn't execute it.
// starts session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
LIMIT 1
";
$result = $conn->query($sql);
$row = $result->fetch_object();
// setting variable values during session
$_SESSION['og_users.username'] = $row->USER_NAME; // Change to correct column name in table og_users
$_SESSION['pacra_teams.title'] = $row->TITLE_COLUMN_NAME; // Change to correct column name in table pacra_teams
The result will be the same every time without a WHERE clause in your sql statement. It's only going to return the first row it finds. It looks like you're trying to set user information in a session variable so you can call the data throughout your application so here's a possible solution assuming you grab an ID for the user somewhere (IE web form).
This is a simple answer to explain a concept, not a tutorial.
<?php
//Setup your connection stuff here
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
//Get a user's name from a form
$userName = $_POST['username'];
// Perform your query
$db= new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
WHERE og_users.username = {$userName} LIMIT 1";
if(!$result = $db->query($sql)){
die('Error [' . $db->error . ']');
}
// Setting variable values during session
while($row = $result->fetch_assoc()) {
$_SESSION['ogUsername'] = $row['USERNAME']; // USERNAME is a placeholder for the example
$_SESSION['pacraTeamsTitle'] = $row['TITLE']; // Same here
}
It's not perfect, but hopefully it helps explain the concept and helps you complete your task.