PHP mysqli increase value - php

I need to say that I'm a beginner on php, mysqli, but I want to learn.
I am trying to build an quiz script which store "SCORE" information into database.
I have the following "final.php" page script, which collects and inserts into the database, the current score of user.
What I need is that I want to keep the current score from database "eg: 213", and increase with current session score which will be "eg :10", so total score after that will be "213(old) + 10(current) = 223(total)
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE users SET scor='".$_SESSION['score']."' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Everything working fine with that code, but all what I need is that to increase score.
Thank you to everyone for you patience and because you understand me that I am beginner.

You can update the existing value in the database by adding your amount to it. There is no need to select the score first.
So in your example:
UPDATE users SET scor=scor + '".$_SESSION['score']."' WHERE id=2
This can be exploited by sql injection, but its out of the scope of the question.

you can use the following statement
$sql = "SELECT scor FROM users (UPDATE users SET scor= scor + '".$_SESSION['score']."' WHERE id=2)";

Related

Delete last record only when a certain URL is present

I have an url as domain.com/abc?orderstatus=cancel
Now, when someone reaches this link, I want to run a query that deletes the last record from the database.
So this is what I tried:
<?php
// Code here for the way to connect to database and insert records which works
// Now I added this code so that only if its on the domain.com/abc?orderstatus=cancel url, it will delete the last record.
$orderstatus = $_GET['orderstatus'];
if($orderstatus == 'cancel') {
$sql3 = "delete from table order by CustomerID desc limit 1";
}
?>
However, this is not working for me. May I know what am I doing wrong?
ps: I tried to cut out as many sql codes which work so that it makes reading easy. If there is any info that I am missing, please do let me know and I'll put it in.
You can use MAX() for MySQL if you have autoincremented on the ID or whatever. MAX() will delete the highest number on the field you specify.
$sql3 = "DELETE FROM table_name
WHERE CustomerID = (SELECT x.id FROM (SELECT MAX(t.CustomerID) AS id FROM table_name t) x)";
//Execute that query
$query3 = mysqli_query($db_conn, $sql3);
If you want to perform DELETE on the basis of ORDER BY then you may have to write nested query. You will get a SQL syntax error if you go with delete from table order by CustomerID desc limit 1
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$orderstatus = $_GET['orderstatus']; // check for sql injections or XSS
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM {YOUR TABLE_NAME} WHERE {YOUR WHERE CLAUSE} ";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>

PHP script, select on server 1 and insert on server 2 if iD doesn't exist (i.e. new records)

We have a phone system database on one server that we cloned/dumped to our local server, but now we need to keep our version updated. Obviously, tables and schema are the same, I just want to run this scheduled script to update with new records that don't exist on the local table (i.e. records that were created since last update).
Below is a test select/insert block. The select query worked on it's own originally, but now I've modified it to use a loop with hopes of using numrows and a foreach to capture everything in the select.
The session table has about 35 columns so I'm looking for the best way to go about this without having to declare every column. I originally tried to do this using update on duplicate key or insert/ignore using a not exists but I don't really know what I'm doing.
Basically, once I select everything, if my table on server 2 doesn't contain a record with the SESSIONID primary key, I want to insert it. I just need some assistance creating this loop script.
Example:
if the table on server 1 has 2 rows with sessionID 12345, and 12346, but my table on server 2 only has up to sessionID 12344, I want to insert the whole records for those two IDs.
//Defining credentials
$servername = "";
$username = "";
$password = "";
$servername2 = "";
$username2 = "";
$password2 = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
$conn2 = new mysqli($servername2, $username2, $password2);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Check connection2
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
echo "Connected successfully";
//Query to select * from Session table on server 1
$query1 = "select * from cdrdb.session";
$results = mysqli_query($conn1, $query1);
foreach ($results as $r => $result) {
$stmt1 = mysqli_prepare($conn2, "insert into ambition.session a where not
exists(a.SESSIONID)");
mysqli_stmt_execute($stmt1) or die(mysqli_error($conn2));
}

SQL statement in php variable?

Ok so I realized this probably looks crazy to good programers but I'm a noob and just trying to figure out the basics. I'm trying to build a simple question/answer site. I can submit a question to the db just fine but when I direct a user to answer I need to put the correct question id (q_id) as it's a foreign key in my answers table. I cant find anything online to solve this problem. I'm sure I'll get "dont use mysqli_query" or something but if anyone can just help me understand how to get the correct value passed into q_id it would be a great help. Seeing my php code below it will probably make sense what I'm attempting to do:
//set up connection credentials
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "ask";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//gather the data from the form
$answer = $_POST["answer"];
$q_id = mysqli_query($conn,"select q_id from questions order by q_id
desc limit 1");
$sql = "INSERT INTO answers (answer, q_id) VALUES ('$answer',
'$q_id')";
if (mysqli_query($conn, $sql)) {
echo "answer submitted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);}
?>
When you open the page that display question, you already use the q_id, just use it again.
Like the stackoverflow URL, question ID is on the URL:
https://stackoverflow.com/questions/44896448/sql-statement-in-php-variable
Because you do not know re-write yet so you can use $_GET method to get q_id.
EDITED:
User insert_id; to get last id after question submitted then you got the id for the question
if (mysqli_query($conn, $sql)) {
$last_id = $conn->insert_id;
echo "answer submitted, id is ".$last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);}
?>

PHP Update MySQL, form input coming through as column name

So I am sorry as I feel I ask stupid questions a lot. I am learning as I go but getting there.
I've created a basic HTML form and with the help of a previous answer I've made the PHP and MySQL query. However when I submit the form the input values from the form come up as column names rather than the information to be updated in the row.
In simple terms when the form is submitted if the input is to change first name from James to Josh the error message is:
"Error updating record: Unknown column 'Josh' in 'field list'"
I though in my SQL query below it would pick up the column name as first_name but this is obviously not happening.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Users";
//Create variables
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$ID=$_POST['ID'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE Users SET first_name=$first_name, last_name=$last_name WHERE
ID=$ID";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
I don't know PHP, but I suspect that your problem is that you arent't quoting the value in your update statment. So try something like:
"UPDATE Users SET first_name='$first_name', last_name='$last_name' WHERE ID=$ID"

Update Mysql with more than one edit

So I run this php script as cron jobs updating points for users on scoreboard.
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE scoreboard SET points='23' WHERE id=2500";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
This works fine for only one id at a time. How can I edit 3 id's with different points each? Thanks.
You don't usually update 3 IDs per query in a list of users for a scoreboard. One request at a time works just fine and including 3 won't make it faster, unless these 3 players all have the same score, but you specifically mentioned you wanted 3 IDs with different scores for each.
If it's about performance/efficiency, use prepared statements (mysqli's prepare) and use a loop after your prepare() in which you:
bind() the parameters (each time for a different user/points)
execute()
If you must.. you could...
update scoreboard
set points = case when ID = 2500 then '23'
when Id = 'XXXX' then 'YY'
when ID = 'YYYY' then 'XX' end
where ID in (2500,'XXXX','YYYY')
But single updates make more sense here. You could write the a bulk insert to a temp table and update from that table if you have a thousands of records to update with different values. This may be faster.

Categories