Select query inside a insert query - php

I'm trying to create a insert query which contains a select query. The problem is that it does not seem to work, but they work separately.
The select query select the highest number from the numbers table and then it need to add 1 to it. the $variables is from php.
What am i doing wrong?
INSERT INTO numbers (number, storeID, udid)
VALUES (
(SELECT number
FROM numbers
WHERE storeid = '$var' AND DATE(timestamp) = CURDATE()
ORDER BY number DESC LIMIT 1
) + 1, $var, $udid)

You may create a variable storing the incremented value first
$results = mysqli_query($con, "Select number FROM numbers where storeid= '$var' AND DATE(timestamp) = CURDATE() Order by number DESC LIMIT 1");
if ($row = mysqli_fetch_array($results))
{
extract($row);
$incremented_value = $row['number'] + 1;
}
Then, the number of columns must be identical
INSERT INTO numbers (number, storeID, udid)
VALUES
($incremented_value, $var, $udid)

Related

select rows where same column values start with string, 2 questions

I'm trying to get multiple sums of rows, each sum has a matching column string value, and all the values have a matching 4 character prefix, but it's not working and I could use some help. Also, would CASE be a more or less costly query on the db?
Started with this:
$sql =
"SELECT col1
FROM table
WHERE substr(col1,1,5)='$string'";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query,MYSQLI_ASSOC);
$results = $row['col1'];
$sum1 = count(array_keys($results,'string1'));
$sum2 = count(array_keys($results,'string2'));
Does it work to get the results from the same column that's in the WHERE clause?
In practice, col1 has row values like aaaa_string1, aaaa_string1, aaaa_string2, aaaa_string2, bbbb_string8... so I'm looking to get all col1 results that have the aaaa in an array, then subsequently filter how many exist of each string1 and string2.
Use SUBSTR(col1, LENGTH('$string')+1) to get the part of the column after the prefix, and group by this.
Use LIKE 'prefix%' to match a column beginning with a prefix.
SELECT SUBSTR(col1, LENGTH('$string')+1) AS suffix, COUNT(*) as count
FROM table
WHERE col1 LIKE '$string%'
GROUP BY suffix
Then you can use a loop to create an associative array with all the counts:
$counts = array();
while ($row = mysqli_fetch_assoc($query) {
$counts[$row['suffix']] = $row['count'];
}
var_dump($counts);
Looking at you code seems that you are trying to get the cout for substring 'string1' or 'string2' in col1
"select col1, count(*) as col_count
from table
WHERE substr(col1,1,5)= '$string'
and col1 in ('string1','string2')
group by col1"
You should retrive the result in col_string and col_count
for suffix (assuming char 6 to end)
"select bstr(col1, 6, 100), count(*) as col_count
from table
WHERE substr(col1,1,5)= '$string'
and substr(col1, 6, 100) in ('string1','string2')
group by bstr(col1, 6, 100)"

How could I execute this basic table query in PHP?

Suppose I have a table TABLE:
NAME ID ...
m -1 ...
f -1 ...
g -1 ...
b -1 ...
z -1 ...
And I want to turn it into:
NAME ID ...
f 1 ...
g 2 ...
m 3 ...
b -1 ...
z -1 ...
You probably get the idea:
select the first 3 rows from the original table (preserving order)
order selected rows by the NAME column.
update selected rows' IDs with their position in the new table (keeping the remaining unselected rows in their original positions).
So (m, f, g) got sorted to (f, g, m) and (b, z) remained (b, z).
Here's how I am trying to do it in PHP:
$count = 0;
$query = "UPDATE TABLE SET ID = $count:= $count + 1 ORDER by NAME DESC LIMIT 3";
mysqli_query($con, $query);
But I don't think I can just go ahead and increment a counter and store its value like that. Any advice?
You can try this :
$limit = 3;
for($count = 0 ; $count < $limit;$count++ ){
$query = "UPDATE TABLE SET ID = $count + 1 WHERE ID = '-1' ORDER by NAME DESC";
mysqli_query($con, $query);
}
$query = "UPDATE TABLE SET ID = '-1' WHERE ID > $limit ORDER by NAME DESC";
mysqli_query($con, $query);
In the above logic :
In the final loop, all the IDs are set to $limit
However the update command outisde the loop will set back IDs to -1 again
First, you can quickly query for the first 3 rows in the table and get the name property only and assign the value in an array.
$sql = "select name from table order by name limit 3"
$query = $mysqli->query($sql);
Now let's construct a helper array:
while ($row = $mysqli->fetch_assoc()) {
$a[] = $row['name'];
}
Now just structure the queries:
foreach($a as $id => $name) {
$query = "update table set id={$id+1} where name='$name' limit 1";
// execute the query
}
Note that I assume that the name is unique so I added the limit 1 directive to tell it stop looking for rows to update once it has found a row.
Also, don't forget that array keys are counting starting from 0, hence we are adding 1 to the $id in the loop.
There may be more elegant solutions but this one is rather easy to understand and use.
In MySQL:
SET #row_number = 0;
update TABLE d
join
(
select
NAME,
#row_number:=#row_number+1 as ID,
from
(select NAME from TABLE limit 3) t
order by
NAME asc
) s on s.NAME = d.NAME
set d.ID = s.ID;
SQLFiddle: http://sqlfiddle.com/#!9/dffecf/1
This assumes NAME is your unique key, otherwise likely best to replace with an Identity column in your table and use that for the update.
This approach may require some syntax changes depending on your DB engine. By doing this in SQL, we only make one pass at the DB. Not a huge deal to iterate in multiple passes with PHP if you're only updating three records, but if it was a 1000, etc.

Query multiple totals at once in MYSQL PHP

I have a a table in my DB that has multiple columns with numbers I would like to query all the rows in 1 query with separate totals for all rows in each column in my db.
like so
$sql = '
SELECT sum(TOTAL1)
, sum(TOTAL2)
, sum(TOTAL3)
, sum(TOTAL4)
FROM TABLE WHERE ID = '.$ID.'';
it works when I do it with a single column query like this.
$sql = 'SELECT sum(TOTAL1) FROM TABLE WHERE ID = '.$ID.'';
but I can't seem to get it to work for multiples in 1 query does anyone know of a more proper way of doing this instead of in separate queries?
$sql = 'SELECT (sum(TOTAL1)+sum(TOTAL2)+sum(TOTAL3)+sum(TOTAL4)) AS FINALTOTAL FROM TABLE WHERE ID = '.$ID.'';
Use aliases.
Sidenote: Add your WHERE clause to the tested examples I've given below.
SELECT sum(TOTAL1) as total1, sum(TOTAL2) as total2
which if you want to use seperate aliases, is handy if you wish to echo them as different entities.
For example:
$query = mysqli_query($con, "SELECT SUM(col1) as total1,
SUM(col2) as total2,
SUM(col3) as total3 FROM table ");
while($row = mysqli_fetch_array($query)){
echo $row['total1']; // echo'd 125
echo "<br>";
echo $row['total2']; // echo'd 225
echo "<br>";
echo $row['total3']; // echo'd 2000
}
Sidenote: My three columns contained the following:
col1 in 2 rows 25, 100
col2 in 2 rows 25, 200
col3 in 2 rows 1000, 1000
To echo the total of all rows and for example: (and inside the while loop)
$total = $row['total1'] + $row['total2'] + $row['total3'];
echo $total;
Or in one go and as one alias and one row echo'd:
SELECT sum(TOTAL1 + TOTAL2 + TOTAL3) as total FROM table
I.e.:
$query = mysqli_query($con, "SELECT SUM(col1 + col2 + col3) as total FROM table ");
while($row = mysqli_fetch_array($query)){
echo $row['total'];
}
NOTE: DATA TYPE must be same for all fields which you want to SUM
By following query you can have SUM(field1)+SUM(field2)+ SUM(field3) .....n in 1 single field
I used this query for just 2 fields and both are integers
See this is my table definition
create table `siso_area_operativa` (
`id_area_operativa` int ,
`area_operativa` varchar (8),
`responsable` int
);
and this is query which you want
SELECT SUM(a.field1) FROM
(
SELECT
SUM(id_area_operativa) field1
FROM
siso_area_operativa
UNION ALL
SELECT SUM(responsable) field1
FROM
siso_area_operativa ) AS a
Result of this is
SUM(id_area_operativa) + SUM(responsable) in single field
ENJOY !!!!!!!!!!!!

Count how many times a specific value is retrievied from a SQL QUERY

MySQL table: name, salary, childrens, brothers, age
I'm trying to retrieve the name of the person who has the max value in salary, childrens and brothers, with age>30. Note: every name is unique.
To do achieve this I loop through all columns whit this array:
$columns = array('salary','childrens','brothers')
foreach($columns as $value){
$result=mysql_query("SELECT `name`, `$value` FROM table_name WHERE `age`>30 ORDER BY `$value` ASC LIMIT 1");
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
echo $rows[name];
};
};
Everything works fine, but I would also like to count the amount of times each name is retrived (echoed).
i.e.: Max has the highest salary and the highest amount of brothers, so his name has been retrivied 2 times. Loren only has the highest amount of childrens, so his name has been retrivied 1 time. Jason has never been retrivied, so it's 0 for him.
I tried this:
$i=0;
$columns = array('salary','childrens','brothers')
foreach($columns as $value){
$result=mysql_query("SELECT `name`, `$value` FROM table_name WHERE `age`>30 ORDER BY `$value` ASC LIMIT 1");
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
echo "The person who has the max amount of $value is $rows[name]";
$count[$rows[name]] = $i++;
};
};
But it doesn't work as intended, it counting the number of times eache name appears in every columns without taking into account if it has the max value.
Any help would be appriciated.
ps: if you also can improve the code the retrivie the max value I would be grateful.
UPDATE:
The query for each table should output this:
Name salary
Max 2000
--
Name childrens
Loren 4
--
Name brothers
Max 3
The $count array should be:
$count = array('Max'=>2,'Loren'=>1,'Jason'=>0,'etc'=>0);
You used the same counter for all names. Try to split them. Something like that:
$count=array();
$columns = array('salary','childrens','brothers')
foreach($columns as $value) {
$result=mysql_query(
"SELECT `name`, `$value`
FROM table_name
WHERE `age`>30
ORDER BY `$value` ASC
LIMIT 1"
);
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)) {
echo "The person who has the max amount of $value is $rows[name]";
if(!isset($count[$rows[name]]))
$count[$rows[name]] = 0;
++$count[$rows[name]];
};
};
print_r($count);
UPD: And also if you need a row with MAX value, you must use DESC instead of ASC
UPD2: To retrieve all the users, you need also execute SELECT DISTINCT name FROM table_name before previous code and fetch it into array $count[$r['name']] = 0
I'm not sure what you up to , but in programing i will use comparing method to get highest value , but there is another MAX() function in server side language to get greatest value of all record http://www.w3schools.com/sql/sql_func_max.asp
$columns = array('salary','childrens','brothers');
$highest = array(array('salary'=>0,'childrens'=>0,'brothers'=>0));
foreach($columns as $value){
$result=mysql_query("SELECT `name`, `$value` FROM table_name WHERE `age`>30 ORDER BY `$value` ASC LIMIT 1");
while($rows=mysql_fetch_array($result,MYSQL_ASSOC)){
//compare the value of each record if greater then replace
if($highest[$value]<$rows[$value]){
//replace with current highest value and set name into array
$highest[$value]=$rows[$value];
$highest[$value]=$rows[name];
}
};
};
print_r($highest);

Get total rows count of table

I want to get all rows count in my sql.
Table's first 2 columns look like that
My function looks like that
$limit=2;
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $total, $datetime, $title, $content);
$stmt->store_result();
$count = $stmt->num_rows;
if ($count > 0) {
while ($stmt->fetch()) {
Inside loop, I'm getting exact value of $total, but MySQL selects only 1 row - row with id number 1. (and $count is 1 too)
Tried this sql
SELECT id,dt,title,content FROM news ORDER BY dt DESC LIMIT 2
All goes well.
Why in first case it selects only 1 row? How can I fix this issue?
for ex my table has 5 rows. I want to get 2 of them with all fields, and get all rows count (5 in this case) by one query.
Remove COUNT(*). You will only ever get 1 row if you leave it in there.
Try adding GROUP BY dt if you want to use COUNT(*) (not sure why you're using it though).
EDIT
Fine, if you insist on doing it in a single call, here:
$sql = "SELECT id,(SELECT COUNT(id) FROM news) as total,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
This is likely cause by the variable $limit being set to 1, or not being set and mysql defaulting to 1. Try changing your first line to
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC";
EDIT
Change to:
$sql = "SELECT SQL_CALC_FOUND_ROWS,id,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
And then use a second query with
SELECT FOUND_ROWS( )
to get the number of rows that match the query
This totally wreaks of a HW problem... why else besides a professor's retarded method to add complexity to a simple problem would you not want to run two queries?
anyways.... here:
SELECT id, (SELECT COUNT(*) FROM news) AS row_count, dt, title, content FROM news ORDER BY dt DESC LIMIT

Categories