PHP MySQL select field and increment the value - php

I want to get the value of specified field(it's INT) then increment this value and then update this in mysql. I tried this but it doesn't work. I'am completely green in MySQL.
$attempts = mysql_fetch_array(mysql_query("SELECT attempts FROM employees WHERE lastname='$lastname'"));
mysql_query("UPDATE employees SET attetmps='$attemtps++' WHERE lastname='$lastname'");

I suggest:
mysql_query("UPDATE employees SET attempts = attempts + 1 WHERE lastname = '".$lastname."'");

if you want to use mysql_fetch_array you should know it returns an array and not one value
so try this
<?php
$query = mysql_query("SELECT attempts FROM employees WHERE lastname='$lastname'");
$row = mysql_fetch_array($query, MYSQL_ASSOC);
$attempts = $row['attempts'] + 1;
mysql_query("UPDATE employees SET attempts='$attempts' WHERE lastname='$lastname'");
?>
or use one query.. you do not need to do two queries
mysql_query("
UPDATE employees
SET attempts = attempts + 1
WHERE lastname = '".$lastname."'
");

UPDATE employees SET attempts = attempts + 1 WHERE lastname = '$lastname'

Related

Calling a function for each MySQL row

I have a standard MySQL database, with around 60 rows (as in user accounts). When I first made it I made the mistake of making session IDs the same as the simple account ID, now I want to fix my mistake and I am obviously not going to go through 60 rows to reset them different secure session IDs, so I am writing this function:
function generate_sessionid(){
return bin2hex(openssl_random_pseudo_bytes(32));
}
function assign_all_sessionids(){
$sessionid = generate_sessionid();
$conn = sql_connect();
$result = mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE 1");
sql_disconnect($conn);
}
assign_all_sessionids();
Problem: Every account in the database gets the same random session ID as the rest. How do I make it recall the function for each row in order to allow it to be random for each row?
Try get user's count from DB and simply execute it N times
function assign_all_sessionids(){
$conn = sql_connect();
// getting users count
// here just change 'id' to your id parameter
$result = mysqli_query($conn, "SELECT id FROM accounts");
$arr = $result->fetch_array(MYSQLI_NUM);
// executing N times
for($i = 0; $i < $result->num_rows; $i++){
$sessionid = generate_sessionid();
// here just change 'id' to your id parameter again
mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE `id`=".$arr[$i]);
}
sql_disconnect($conn);
}
You can do what you want by first setting all the session ids to NULL:
UPDATE accounts
SET sessionid = NULL;
Then, inside the loop:
UPDATE accounts
SET sessionid = '$sessionid'
WHERE sessionid IS NOT NULL
LIMIT 1;
Normally you don't want to execute queries in a loop, however in this case you need to get all of the current unique identifiers, loop and generate a new identifier and then update one:
function assign_all_sessionids(){
$conn = mysqli_connect('whatever...');
$select = mysqli_query($conn, "SELECT sessionid FROM accounts");
while(list($id) = mysqli_fetch_assoc($select)) {
$sessionid = generate_sessionid();
$update = mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE sessionid='$id'");
}
}

Getting last value of a field in mysql

I am trying to get the last value of a field during a new registration.
before insert data into the table, I want to create a user id number according to the last registered user's id number. to do that I use this:
//to reach the last value of userID field;
$sql = "SELECT userID FROM loto_users ORDER BY userID DESC LIMIT 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$value = $row['userID'];
echo "$value"; //not resulting here
}
$userID = $value+1;
so, the userID becomes 1.
The weird thing is, I could capable to use exact same code in another php file and works fine.
I would like to say that, rest of the code works fine. No problem with db connections or any other things you can tell me.
Note that: When I run the same query line in the mysql interface, I can get the value I want. I mean $sql line.
Your problem is in this code:
{
$svalue = $row['userID'];
----^
echo "$value"; //not resulting here
}
$userID = $value+1;
Change to $value.
But the right answer is to define userID to be auto-incrementing. That way, the database does the work for you. After inserting the row, you can do:
SELECT LAST_INSERT_ID()
To get the last value.
I solved the problem. Here;
$sql = "SELECT userID FROM loto_users ORDER BY userID DESC LIMIT 1";
$result = mysql_query($sql);
$user_info = $result->fetch_assoc();
$value = intval($user_info["userID"]);
$userID = $value+1;
Thanks everyone.
If you mark the userID field as autoincrement in you mysql table.
You won't need to set the userID and db increase the userID for you. You can get the assigned userID using the mysql_insert_id() function. Here is an example from php.net
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
Here is another example for your case
mysql_query("INSERT INTO 'loto_users'('username',...) values('usernameValue',...)");
echo "New User id is ".mysql_insert_id();

Update table based on condition (While Loop)

So I am trying to update my table based on a singe parameter:
The dateEntered field must be blank.
And I want to randomly select 50 rows, and update the blank ownerID fields to "Tester"
Here is what I have:
<?php
include("includes/constants.php");
include("includes/opendb.php");
$query = "SELECT * FROM contacts WHERE dateEntered='' ORDER BY RAND() LIMIT 50";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$firstid = $row['id'];
$query2 = mysql_query("UPDATE contacts
SET ownerID = 'Tester'
WHERE id = '$firstid'");
$result2 = mysql_query($query2) or die(mysql_error());
}
?>
It will update a single record, then quit and give me:
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 '1' at line 1
The first part that selects the records works fine, its query2 that won't update all 50 records, just one. Maybe I am writing this wrong.
mysql_query needs only one time
$query2 = mysql_query("UPDATE contacts
SET ownerID = 'Tester'
WHERE id = '$firstid'");
$result2 = mysql_query($query2) or die(mysql_error());
to
$result2 = mysql_query("UPDATE contacts
SET ownerID = 'Tester'
WHERE id = '$firstid'");
These answers are spot on, so I will only add some additional information, and a suggestion. When you are querying mysql the first time, $query1 is being set to the result resource, which for
$query1 = mysql_query("UPDATE contacts SET ownerID = 'Tester' WHERE id = '$firstid'");
returns a result of 1 (Boolean TRUE), which is why your second query failed, cause "1" isn't a valid mysql query string. As Greg P stated, you can fix your current script by eliminating the secondary mysql query.
However, you could improve the script entirely, and make fewer sql calls, by using this.
<?php
include("includes/constants.php");
include("includes/opendb.php");
$query = "UPDATE contacts SET owenerID='Tester' WHERE dateEntered='' ORDER BY RAND() LIMIT 50";
$result = mysql_query($query) or die(mysql_error());

Updating records If ipAddress and playerName match

At the moment im sending scores and data to my database from my flash game, though every level completed is a new record.
feilds are set out like l1Score,l2Score,l3Score
im trying to figure out how to update records if the field ipAddress and playerName match the current $varibles.
UPDATE highscores SET l2Score = '$l2Score' WHERE ipAddress = "$ipAddress" && playerName = '$playerName'
I was thinking somthing along these lines, but could someone point me in the right direction please!
First you want to perform a query to check if there is already a score in place for that user & IP.
$sql = "SELECT * FROM highscores WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
$result = mysql_query($sql, $con);
$row = mysql_fetch_assoc($result);
Now, if $row is empty then you want to insert a new record, else you want to update a previous record.
if($row == "")
{
$query = "INSERT INTO highscores (l2score, ipAdress, playerName) VALUES ('$l2score', '$ipAdress', '$playerName'";
} else {
$query = "UPDATE highscores SET l2Score = '$l2Score' WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
You may need to edit this to fit with the specific query that you need.

Can't get SQL Update to work using PHP

I'm trying to get php to update a MySQL table using UPDATE statement but it simply won't work. Here's the code I wrote:
$add = "1";
$counter=mysql_query("SELECT * FROM frases WHERE id = '".$id."'");
while ($ntcounter=mysql_fetch_array($counter)) {
mysql_query("UPDATE frases SET count = '".$ntcounter[count]+$add."' WHERE id = '".$id);
}
As you can see, I am basically trying to update the SQL record to keep track of how many times a specific content ID was visited.
Thanks!
Use an alias in your SQL query (It is not mandatory, but it makes the query much more readable.)
SELECT * as count FROM frases WHERE id = '".$id."'"
And you can now access to your variable
$ntcounter['count']
So the result :
$add = "1";
$id = (int)$id
$counter = mysql_query("SELECT * as count FROM frases WHERE id = '".$id."'");
while ($ntcounter = mysql_fetch_assoc($counter)) {
mysql_query("UPDATE frases SET count = '".($ntcounter['count']+$add)."' WHERE id = '".$id);
}
You don't really need two queries. You should just be able to update like this
mysql_query("UPDATE frases SET `count` = `count` + 1 WHERE id = ".$id);
You didn't close the single quote at the end of the update statement:
mysql_query("UPDATE frases SET count = '".$ntcounter[count]+$add."' WHERE id = '".$id."'")

Categories