In PHP, I'm using mysqli_affected_rows to validate whether a user has been registered in a database, where a query looks something like this:
"UPDATE schedule WHERE userid = '$user' AND date='2018-05-05'"
If the user doesn't exist, the number of affected rows is 0, and if they do exist, it's 1.
This works OK, except for when a user is registered in a second time. Here, MySQL will say 0 rows are affected, since there has been no change to the schedule.
Is there anything I can add to my query to always affect rows? Or is this just a poor approach?
To check whether a user exists in a database, I would use a select statement instead.
sql = "SELECT * FROM schedule WHERE userid = '$user' AND date='2018-05-05'"
Then do something if a user exists
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//user exists
}
I would also assume you would like to have unique users in the database? I that case I would check whether a user exists first using the same code before adding a new record.
Related
I want to only run the update query if row exists (and was inserted). I tried several different things but this could be a problem with how I am looping this. The insert which works ok and creates the record and the update should take the existing value and add it each time (10 exists + 15 added, 25 exists + 15 added, 40 exists... I tried this in the loop but it ran for every item in a list and was a huge number each time. Also the page is run each time when a link is clicked so user exits and comes back
while($store = $SQL->fetch_array($res_sh))
{
$pm_row = $SQL->query("SELECT * FROM `wishlist` WHERE shopping_id='".$store['id']."'");
$myprice = $store['shprice'];
$sql1 = "insert into posted (uid,price) Select '$uid','$myprice'
FROM posted WHERE NOT EXISTS (select * from `posted` WHERE `uid` = '$namearray[id]') LIMIT 1";
$query = mysqli_query($connection,$sql1);
}
$sql2 = "UPDATE posted SET `price` = price + '$myprice', WHERE shopping_id='".$_GET['id']."'";
$query = mysqli_query($connection,$sql2);
Utilizing mysqli_affected_rows on the insert query, verifying that it managed to insert, you can create a conditional for the update query.
However, if you're running an update immediately after an insert, one is led to believe it could be accomplished in the same go. In this case, with no context, you could just multiply $myprice by 2 before inserting - you may look into if you can avoid doing this.
Additionally, but somewhat more complex, you could utilize SQL Transactions for this, and make sure you are exactly referencing the row you would want to update. If the insert failed, your update would not happen.
Granted, if you referenced the inserted row perfectly for your update then the update will not happen anyway. For example, having a primary, auto-increment key on these rows, use mysqli_insert_id to get the last inserted ID, and updating the row with that ID. But then this methodology can break in a high volume system, or just a random race event, which leads us right back to single queries or transaction utilization.
I want to be able to bring back the earliest logon time per user, so only 1 record (the earliest record) displays for each user
I've tried various ways of GROUP BY but can't seem to get it quite right (if that is actually the correct way of doing). username is the unique value which can be used to GROUP BY
Here's the code I'm currently working with..
SELECT username, name, logon, added FROM data WHERE (date(added) LIKE '$date') AND (logon = (SELECT MIN(logon) FROM data))
I've also tried (below) but only get one result back, only displaying one user
WHERE (date(added) LIKE '$date') AND logon = (SELECT MIN(logon) FROM data)
The first image is what I'm currently getting, the second image is how I want my results to display, please see below
Let me know if you require anymore information, I've tried to put as much as possible
Thanks,
Tom
You are close. Your query needs a correlation clause:
SELECT d.*
FROM data d
WHERE date(d.added) = '$date' AND
d.logon = (SELECT MIN(d2.logon) FROM data d2 WHERE d2.name = d.name);
Note: The logic for added is confusing. First, you should not use like with dates. And, for that matter, you should not be inserting parameter values into the string, you should be using query parameters. And, actually, I don't see the need for that column; your question doesn't mention added.
use this query , problem will be solved
SELECT username, min(logontime) FROM data where date(logontime) = '2016-08-10' group by username
do this:
<?php
$users = array();
$sql = "select * from users";
$result= mysqli_query($conn,$sql);//$conn is your connection object
while($user = mysqli_fetch_assoc($result)){
if(!in_array($user['name'],$users)){
$users[$user['name']]=$user['logOnTime'];//replace key names with your table row names
}
}
//$users is an array that has your user names as key and their last logon time as value
?>
I'm collecting the birthdates of users in my system, doing so by linking the the user's unique ID to their birthday entry in another table.
To prevent users from accidentally/purposefully entering two birthdate entries for their accounts, I'd like to remove to the entry form for birthdays IF the user has already entered a birthday prior.
For instance:
$value = mysqli_query("SELECT bd_user_id FROM user_birthdate WHERE
bd_user_id="$user_id";");
From that data, how will I be able to return some form value to determine if whether the user's ID has already been index in user_birthdate or not? (Where $user_id = The current user's ID)
Or perhaps I'm taking the wrong approach here? The logic behind it is what's been getting me.
How can I check if whether a value is NOT indexed in a database table?
You normally query the database as you did
$value = mysqli_query("SELECT bd_user_id FROM user_birthdate WHERE bd_user_id="$user_id";");
Than you use mysqli_num_rows(), and check if it returns 0.
$num_rows = mysqli_num_rows($value);
if($num_rows > 0){
//exists
}else{
//doesn't exist
}
**Sorry, as Devon said in your case it's mysqli_num_rows not mysql_num_rows.
I'm trying to lock a row in a table as being "in use" so that I don't process the data twice when my cron runs every minute. Because of the length of time it takes for my script to run, the cron will cause multiple instances of the script to run at once (usually around 5 or 6 at a time). For some reason, my "in use" method is not always working.
I do not want to LOCK the tables because I need them available for simultaneous processing, that is why I went the route of pseudo-locking individual rows with an 'inuse' field. I don't know of a better way to do this.
Here is an illustration of my dilemma:
<?
//get the first row from table_1 that is not in use
$result = mysqli_query($connect,"SELECT * FROM `table_1` WHERE inuse='no'");
$rows = mysqli_fetch_array($result, MYSQLI_ASSOC);
$data1 = $rows[field1];
//"lock" our row by setting inuse='yes'
mysqli_query($connect,"UPDATE `table_1` SET inuse='yes' WHERE field1 = '$data1'");
//insert new row into table_2 with our data if it doesn't already exist
$result2 = mysqli_query($connect,"SELECT * FROM `table_2` WHERE field='$data2'");
$numrows = mysqli_num_rows($result2);
if($numrows >= 1) {
//do nothing
} else {
//run some unrelated script to get data
$data2 = unrelatedFunction();
//insert our data into table_2
mysqli_query($connect,"INSERT INTO `table_2` (field) value ('$data2')");
}
//"unlock" our row in table_1
mysqli_query($connect,"UPDATE `table_1` SET inuse='no' WHERE field1 = '$data1'");
?>
You'll see here that $data2 won't be collected and inserted if a row already exists with $data2, but that part is for error-checking and does not answer my question as the error still occurs. I'm trying to understand why (if I don't have that error-check in there) my 'inuse' method is sometimes being ignored and I'm getting duplicate rows in table_2 with $data2 in them.
There's a lot of time in between your first select and the first update where another process can do the same operation. You're not using transaction either, so you're not guaranteeing any order of the changes becoming visible to others.
You can either move everything into a transaction with the isolation level you need and use SELECT .... FOR UPDATE syntax. Or you can try doing the copy in a different way. For example update N rows that you want to process and SET in_use=your_current_pid WHERE in_use IS NULL. Then you can read back the rows you manually marked for processing. After you finish, reset in_use to NULL.
I am having endless troubles with duplicate entries, so I need to check the database, and if a user has already entered that day, their entry will not be submitted and they will be redirected to a landing page that tells them they have already entered that day, and that they may only enter again tomorrow.
The field I would like to check is the id_number field in the database, since each user has a unique id number, so basically, if a user with the same id number submitted on the same date they should be redirected to a landing page, how would I go about doing this? I am still new to a lot of this, so please be forgiving.
Thanx in advance.
before you submit your sql query to add a new record you can read the DB first to make sure the ID is not already in there. Get the users id into a variable and do this query.
$query = "select * from mytable where `id` = '$id'";
$result = mysql_query($query);
then you can count the number of records returned and do different things depending on the result, checking that its zero before adding them. If its not zero then redirect.
if(mysql_num_rows($result) > 0)
{
//add them
}
else
{
//redirect them
}
Hope this helps you out