views:

58

answers:

2
+2  Q: 

MySQL condition

I'm still pretty new with MySQL and I don't know the best way to do this.

I have a table with incremented values, and if the values exceed a certain limit, I'd like to know. So lets say I have this table with a current column and capacity column. A row in current is incremented by user input and I want to know when the value in a current row exceeds or meets its corresponding capacity.

If current is still below the capacity, I would like the query to return true. However, if current meets or exceeds capacity, I would like the query to return false.

Thanks!

+4  A: 

in mysql that's easy:

select (current >= capacity) as exceeded from table
knittl
Is => a valid operator in MySQL now, or did you mean >= ?
Mark Baker
woops. of course i meant `>=`
knittl
Shouldn't this return true only when `current < capacity`?
BoltClock
Thank you for the replies. I'm actually using UPDATE on the row. How would I apply this to an UPDATE query? Thanks!
tau
@tau: update does not return anything
knittl
+2  A: 

Add a WHERE clause to do that check in your UPDATE query:

// I assume you mean you want to increment the current column by 1,
// but it's your table so change the SET values as needed
$updated = mysql_query('UPDATE table SET current = current + 1 WHERE id = ' . intval($row_id) . ' AND current < capacity');

Then check mysql_affected_rows() of the UPDATE query:

if (mysql_affected_rows() > 0)
{
    // Success
}
BoltClock
Thanks! This is just what I needed. I have one question, though. Whenever I put the variable associated with my `mysql_query` in `mysql_affected_rows`, it wouldn't work (says it wasn't valid MySQL resource). When I removed it and used `mysql_affected_rows()` without an argument, it worked! Do you know why?? Thanks!
tau
Because it was a mistake on my part: the variable isn't supposed to be there. I've edited my answer to remove it. Sorry for the confusion! Glad my solution worked for you though :)
BoltClock