Read the SQL table row and add 1 to the result

I am trying to count a table row and add 1 to the result, I have this piece 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 an error:

Fatal error: unsupported operand types

I need this, so I always have a unique number that was not used by the previous donor.

+4
source share
4 answers

use simple php

 $countQuery = mysql_query("SELECT id FROM donations"); $count=mysql_num_rows($countQuery); $count+=1; 
+3
source

You can use:

 SELECT COUNT(id)+1 as IDCount FROM donations 

as your request. This will save you from any errors in PHP to do the math. The array you are retreating from will have the number you want right off the bat.

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

Using this, you never need to insert a value, but you pass it NULL as follows (assuming the identifier is a field with Auto_increment on it:

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

So, you see that you are not giving it any values ​​for the ID column - the database takes care of the correct number.

+6
source

It is dangerous to rely on COUNT to give you a unique number. What happens if two processes execute this query and then both try and commit: you suddenly get the same value twice.

It would be much safer to implement some sequence function that is independent of the contents of your table. This link shows one possibility:

http://forums.mysql.com/read.php?61,143867,238482#msg-238482

+1
source

This question is for a MySQL database. I suggest you use the AUTO INCREMENT field type. Since you are using PHP, if you need to know the identifier after inserting the record, use:

 mysql_query("INSERT INTO mytable (1, 2, 3, 'blah')"); $id = mysql_insert_id(); 

See mysql_insert_id() .

Using

4 random numbers to make 100% sure that there are no duplicates

will not make 100% sure that there are no duplicates. Do not reinvent the wheel. Thus, the problem of providing unique incremental identifiers was solved, you do not need to confuse the homebrew solution, which does not always work.

0
source

Source: https://habr.com/ru/post/1434185/


All Articles