Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count SQL table row and add 1 on the outcome

Tags:

sql

php

mysql

count

I'm trying to count a table row and add 1 on the outcome, I have this snippet of code.

$countQuery = "SELECT COUNT(id) FROM donations";
$outcomeQuery = mysql_query($countQuery);
$countUp = mysql_fetch_array($outcomeQuery);
$plusOne = 1; 
$outcome = $countUp;
echo $outcome[0]
    or die(mysql_error());

But this gives me the error:

Fatal error: Unsupported operand types

I need this so I always have a unique number that's not used by a previous donator.

like image 846
Laetificat Avatar asked Dec 26 '22 17:12

Laetificat


1 Answers

You could use:

SELECT COUNT(id)+1 as IDCount FROM donations

as your query instead. This will save you any mucking about in PHP to do the math. The array you pull back will have the number that you want right off the bat.

Edit: The better alternative however is to use a column type that increments automatically. In MySQL, this is done with the syntax auto_increment in the create table syntax.

Using this, you never actually have to insert a value, but rather, you pass it a NULL as follows (assuming that ID is the field with Auto_increment on it:

insert into tableName (ID,Name) values (null, 'Fluffeh');

So you see you don't give it any values for the ID column - the database takes care of using the right number.

like image 70
Fluffeh Avatar answered Jan 08 '23 06:01

Fluffeh