Best way to update a single column in MySQL table? - php

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

Related

How to add column value plus users input in PHP update query

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

How to update specific rows by comparing timestamps?

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);
?>

Connect Multiple Database with PHP and MySQL

We have this multiple database and we need to connect all of them together. We are using relationship table to talk back and forth. Multiple database will help us to backup the project or version separately.
Registration database: User Log In
Project database: Number of projects under the Logged in user.
Version database: Number of versions under the selected Project
THE ISSUE
Because we are using 0 and 1, only one user can able to connect to the database at a time. What we need is like the one in the flowchart below. Multiple user can able to connect to the database and working on a different project > different versions.
Thanks!
Sidenote: We are open to try different approach
<?php
//database error message
$connect_error='We could not able to connect. Please try later';
// Registration table
$main = mysql_connect('localhost','root','',true) or die($connect_error);
mysql_select_db('registration-table', $main) ;
// Obtaining session id
if(isset($_SESSION['id'])===true){
$session = $_SESSION['id'];
// Filtering projects based on 0 and 1
$sql = mysql_query("SELECT * FROM project1_table where user_id = '$session' and database_active = '0'",$main);
$row = mysql_fetch_array($sql);
// Each Project has Versions
$project_id = $row['id'];
$sqli = mysql_query("SELECT * FROM version_table where project_id = '$project_id' and database_active ='0'",$main);
$emp = mysql_fetch_array($sqli);
// Fetching the database name
$db_name = $emp['database_name'];
$sub = mysql_connect('localhost','root','',true) or die($connect_error);
mysql_select_db("$db_name", $sub) ;
}
?>
First of all I would suggest you to use mysqli or PDO other then mysql , Because after PHP 5.5 version mysql function deprecated and therefore mysql function will not be available in future
Multiple DB connection in Mysql
$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);
mysql_query('select * from tablename', $dbh1);
mysql_query('select * from tablename', $dbh2);
Multiple connection using Mysqli
$link1 = new mysqli($hostname, $username, $password,$database1);
$link2 = new mysqli($hostname, $username, $password,$database2);
mysqli_query($link1,"SELECT * FROM table");
mysqli_query($link2,"SELECT * FROM table");
Multiple DB connection in PDO
$conn1 = new PDO("mysql:host=$hostname;dbname=database1", $username, $password);
$conn2 = new PDO("mysql:host=$hostname;dbname=database1", $username, $password);
$conn1->query("SELECT * FROM table");
$conn1->query("SELECT * FROM table");
$conn1 = mysqli_connect( $db_host, $db_user, $db_pass, $db_name );
$conn2 = mysqli_connect( $db_host2, $db_user2, $db_pass2, $db_name2 );
Let's say you have a database named chat1 and chat2, and a table named tbl_chat1 and tbl_chat2.
$sql1 = "SELECT `id`, `msgs` FROM `chat1` . `tbl_chat1`";
$sql2 = "SELECT `id`, `msgs` FROM `chat2` . `tbl_chat2`";
$result1 = mysqli_query($conn1, $sql1);
$result2 = mysqli_query($conn2, $sql2);
However you can achieve the backup of your database without having to connect to multiple databases OK.

MySqli not working correctly

My goal is to recieve 2 strings, an IP and UUID, and look in the database. If the UUID is already there, it adds the IP onto a list of IPs in the database. If not, it makes a new row in the database with that UUID and IP. Purpose is tracking user activity (Nothing malicious)
Code:
<?php
$cip = $_POST['ipaddr'];
$cid = $_POST['id'];
$conn = mysqli_connect('localhost', '*****', '*****', '*****');
$query = mysqli_query($conn, "SELECT * FROM sls WHERE asid='".$cid."'");
if(mysqli_num_rows($query) > 0){
$sql = "SELECT asid, ips FROM sls WHERE asid=$cid";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$cipdata = $row["ips"];
}
$sql = "UPDATE sls SET ips='$cipdata , $cip' WHERE id=2";
mysqli_query($conn, $sql);
} else {
$sql = "INSERT INTO sls (asid, ips) VALUES ('$cid', '$cip')";
mysqli_query($conn, $sql);
}
?>
Right now, it just adds a new row for every IP, regardless of UUID.
What did I do wrong?
-- Edit: Fixed typo, now it just adds the first IP, but after that does not add any more to the row.
Perhaps there is a small typo on this line:
$query = mysqli_query($con, "SELECT * FROM sls WHERE asid='".$cid."'");
Did you mean $conn, not $con? As in:
$query = mysqli_query($conn, "SELECT * FROM sls WHERE asid='".$cid."'");
Your connection param is $conn so just used this in every query command. some where you are using $con and somewhere $conn.
Check your code.

PHP: mysqli_query is not working [duplicate]

This question already has answers here:
php/mysql with multiple queries
(3 answers)
Closed 3 years ago.
I've a doubt with mysqli_query..
this is a part of my code:
$con = db_connect();
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
$result = mysqli_query($con, $sql);
return $result;
I can't do the query...
If I try to do a query like this:
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
It works.
What's the problem?? I can't use SET with mysqli_query?
Thanks
You can not execute multiple queries at once using mysqli_query but you might want to use mysqli_multi_query as you can find out in the official documentation:
http://www.php.net/manual/en/mysqli.multi-query.php
Lets start with creating a working php script.
<?php
// replace for you own.
$host ="";
$user = "";
$password = "";
$database = "";
$con= mysqli_connect($host, $user, $password, $database);
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
// Begin SQL query
$sql = "SELECT * FROM users";
$result = mysqli_query($con,$sql) OR Die('SQL Query not possible!');
var_dump($result);
return $result;
var_dump($result);
// End SQL query
mysqli_close($con);
};
?>
INSERT query:
$sql= "INSERT INTO categorias(name) VALUES ('ssss')";
mysqli_query ($con,$sql) OR Die('SQL Query not possible!');
UPDATE and DELETE query:
$sql= "DELETE FROM users WHERE username = 'Hola';";
$sql.= "UPDATE users SET foreign_key_checks = 0 WHERE username = 'Hola'"; /* I made a guess here*/
mysqli_multi_query ($con,$sql) OR Die('SQL Query not possible!');
Check the SET query. I think something is missing. I have changed it to what I think was your aim.
The connection should be established like this:
$Hostname = "Your host name mostly it is ("localhost")";
$User = "Your Database user name default is (root)"//check this in configuration files
$Password = "Your database password default is ("")"//if you change it put the same other again check in config file
$DBName = "this your dataabse name"//that you use while making database
$con = new mysqli($Hostname, $User , $PasswordP , $DBName);
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
In this query:
put categorias in magic quotes(`) and column names also
For your next query do this:
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
Change to:
$sql= "SET foreign_key_checks = 0; DELETE FROM `users` WHERE `username` = 'Hola'";

Categories