This is very awkward, this is a very simple fetch value, equal to otherwise sum one and then save... but is not working...
I have a predefined value as 1010, so, I select the last entry in the SQL, if the last entry is grater than 1010 then get the value and add 1, then save it which now the last value would be 1011 correct? but is not....
$values_b = 1010;
$getval = 'SELECT number FROM table ORDER BY number DESC LIMIT 1';
$final = $con->query($getval);
$vals = $final ->fetch_array();
$numbers = $vals['number'];
if ($numbers > 1010){
$new_n = $numbers + 1;
$new_numbers = 'INSERT INTO table (number) VALUES ('$new_n')';
$con->query($new_numbers);
} else {
$new_numbers = 'INSERT INTO table (number) VALUES ('$values_b')';
$con->query($new_numbers);
}
Very simple, but the result some how is awkward, it doesn't save 1010 or 1011 or any of the sort... instead is saving 2325 and why is that???? I don't use this values anywhere else, those are unique variables but I really don't understand, this is the first time this is happening, my table is utf-8-general-ci and the column is INT(20) I have try VARCHART(100) but the result is almost the same...
What I'm trying to achieve is "simple", I have a per-defined number 1010, so, if this is the first record save that number 1010, if not, then get the last record say 1020 which mean that there are 10 records, just sum 1 to the last record 1020 + 1 = 1021 and save it... see, very simple, but for some reason is not doing it... so I was wondering if someone can help me solve this...
Thank you for taking the time
SOLVED
The problem here was the query, I was calling to a column with the incorrect name
this table has about 19 columns, the first 5 are
ID | Name | email | numbers ..... the column 16 is | number |
I was calling number when in reality I should be calling for NUMBERS the result that I was getting was from another file, so, in other words, I was getting the result from B and adding 1 to B when I should be using A...
this is entirely my fault, I should paid more attention... sorry guys...
Try this:
$values_b = 1010;
$getval = 'SELECT max(number) as bignumber FROM table';
$final = $con->query($getval);
$vals = $final ->fetch_array();
$numbers = $vals['bignumber'];
if ($numbers > 1010){
$new_n = $numbers + 1;
$new_numbers = 'INSERT INTO table (number) VALUES ('$new_n')';
} else {
$new_numbers = 'INSERT INTO table (number) VALUES ('$values_b')';
}
$con->query($new_numbers);
Related
I want to get 3 random records from my table to 90 times.
Scenario
user_id number_of_bids
12 20
8 40
6 30
what i want is...Get above 3 rows in random order to a specific number In fact it is sum(number_of_bids)...
And every row should not repeated greater than its number of bids..
I have created a query where I am getting sum of number_of_bids.Now second query required where these 3 records should be in random order to sum(number_of_bids) times and every record should not greater repeated greater than its number_of_bids.
Not sure it can be achieved in one query or not.But you people are experts I am sure you can help me.It will save my execution time..
Thanks..
I would just build an array out of the rows and shuffle it:
$stmt = $db->query('SELECT user_id, number_of_bids FROM table_name', PDO::FETCH_KEY_PAIR);
$results = array(); $startIndex = 0;
foreach ($stmt as $userId => $numberOfBids) {
$results += array_fill($startIndex, $numberOfBids, $userId);
$startIndex += $numberOfBids;
}
shuffle($results);
Then, you can iterate $results however you'd like.
I have a PHP document with MySQL database storing with the following structure:
DATE FIELD
24 float values corresponding to the 24 hours. (The name is 1h, 2h, 3h, 4h... 24h)
I fetch a row with the simple select: SELECT * from table where DATE = "2014-02-02" obtaining the 25 fields.
I want to know wich field of 1h, 2h, 3h.... has the lower value. I'm trying doing that with PHP and min() function, but I only retreive the value, not the index of the array.
Is this possible a simple way to know this result? Maybe in the SQL function?
Thank you
EDIT: I tried this (Considering $arraySQL has a valid result obtained before):
function ObtainArrayFromSQL($arraySQL){
$array = array();
for ($i = 1; $i < 25; $i++)
{
array_push($array, $data_day[$i."h"]);
}
return $array;
}
[...]
$array = ObtainArrayFromSQL($arraySQL)
echo min($array);
Assuming you are using MySQL, you can use the least() function:
select t.*,
(case when col1 = leastval then 'col1'
when col2 = leastval then 'col2'
when col3 = leastval then 'col3'
. . .
when col24 = leastval then 'col24'
end) as leastvalcol
from (select t.*,
least(col1, col2, . . . , col24) as leastval
from table t
) t;
Before complaining about all the typing you need, you should know that this query is much more complicated than it needs to be -- because you are storing things on a row that should be in a column. Your table should have a separate row for each hourly value, rather than putting all the daily values on one row. With a more normalized structure, your query would be much simpler.
EDIT:
This table would have columns such as:
Date date,
Hour time, -- or int or varchar() depending on how you really want it captured
Value float
Then the query might look like:
select date, min(value) as minvalue,
substring_index(group_concat(hour order by value asc), ',', 1) as minhour
from newtable t
group by date;
At first, thank you everyone for the help.
Finally I made the solution with PHP instead of manipulate a big SQL sentence.
I create the array using the function ObtainArrayFromSQL, and then, use the function array_search() with min() as needle in the haystack (array).
function ObtainArrayFromSQL($arraySQL){
$array = array();
for ($i = 1; $i < 25; $i++)
{
array_push($array, $data_day[$i."h"]);
}
return $array;
}
...
$index_lower_value = array_search(min($array), $array);
Thank you everyone!
i am not sure if i am doing this correctly, and i am kinda stucked here.
Here's what i want to do, each row in the database has 5 column, say A,B,C,D with each having an integer value out of 10 and E which is like a counter. so what i want is to get an average.
which should be something like below
(A + B + C + D)/(E * 4)
and each of these values calculated above, has to be summed up and divide by the total number of rows.
So say i have 3 entry it has to divided by 3
so what i came up with is
$myresult = mysql_query("SELECT * FROM studies WHERE classes = '$classid'");
list($mycount) = mysql_fetch_row($myresult);
$result = mysql_query("SELECT ID, sum((maths + sciences + moral + bm)/(count*4))/'$mycount' FROM studies WHERE classes = '$classid'");
am i doing this right?
if the sql is right, how am i suppose to print out the result so i can use it as a variable?
thank you
The query should be right, but to get the actual value is easy.
You have to fetch_array the query, and the first variable would be the ID and the second would be the sum.
Example
while($row = mysql_fetch_array($query)){
echo $row[0]; // This is the ID
echo $row[1]; // This is the sum
}
I try to build a variable that integrates some other variable.
one of that will be the number of an auto-increment-field where later on an insert-query will happens.
I tried to use:
$get_num = $db/*=>mysqli*/->query("SELECT COUNT (*) auto_increment_column FROM table1");
$num = $query->fetch_assoc($get_num);
$end = $num + 1;
I don't have any update/insert query before that so I can't use
$end = $db->insert_id;
that's why i thought i can just count the numbers of the auto_increment rows and have my last variable that is necessary to build my new variable.
for a reason this wonT count the entries and outputs 0. i dont understand why this happens.
i really would appreciate if there is someone who could tell me what am i doing wrong. thanks a lot.
UPDATE
For everyone who likes to know about what's the goal:
I like to create a specific name or id for a file that later on will be created by the input of the fields from the insert query. I like to have an unique key. this key consists of an user_id and a timestamp. at the end of this generated variable it should be placed the auto_increment nr. of the query that will be placed in the table. so the problem is, that I create an variable before the insert query happens so that this variable will be part of the insert query like:
$get_num = $db->query("SELECT COUNT (*) FROM tableA");
$num = $query->fetch_assoc();
$end = $num + 1;
$file_id = $id .".". time() .".". $end;
$insert = $db->query("INSERT INTO tableA ( file_id, a, b, c) VALUES('".$file_id."','".$a."','".$b."','".c."')");{
hope now, it will be clear what I like to approach.
If you need an auto-incrementing column in MySQL then you should use AUTO_INCREMENT. It implements it all for you and avoids race conditions. The manual way you are trying to implement it has a couple of flaws, namely
If two scripts are trying to insert concurrently they might both get the same COUNT (say 10) and hence both try to insert with ID 11. One will then fail (or else you will have duplicates!)
If you add 10 items but then delete item 1, the COUNT will return 9 but id 10 will already exist.
try
SELECT COUNT(*) FROM table1
Take this table:
id | field1 | foreign
1 abc 12
2 def 12
3 abc 13
4 def 13
I select this record like this:
"SELECT field1 FROM table WHERE foreign = 12"
AND
"SELECT field1 FROM table WHERE foreign = 13"
Now considering my table this select returns exactly the same records value.
How can I tell that given 2 arbitrary SELECT they retunrs the same value in SQL?
PS. Considering you were voting to close this question I have reformulated it. thanks
PS2. I have other field other than field1
PS3. I know I can do it via PHP, but is there a way pure-SQL?
You can use md5sum to confirm whether 2 result sets are equal or not, this is very useful when comparing two large result sets. Just use the following command within mysql console:
pager md5sum -
This will set the MySQL pager to display the MD5Sum after every query that is run.
If you are using PHP to run each query then you could create the same effect using this method:
// This method will return MD5 of a result set. Compared results will return the same MD5Sum if they have the same results, and are ordered in the same way.
function query_md5($sql) {
$rs = mysql_query($sql);
$num = mysql_num_fields($rs);
$str = "";
while ($obj = mysql_fetch_array($rs)) {
$i = 0;
while ($i < $num) {
// no need for spaces or formatting
$str .= $obj[$i++];
}
}
return md5($str);
}
Hope this helps!