Can you get 2 different results from a single MySQL query? - php

Can I retrieve 2 different (opposite) results from a single mysql query?
Instead of doing something like this in 2 separate queries:
$sql = "SELECT my_column FROM my_table WHERE id = 1";
/*if num_rows > 0, echo rows from $sql*/
$sql2 = "SELECT my_column FROM my_table WHERE id <> 1";
/*if num_rows > 0, echo rows from $sql2*/
Is it possible to do that in a single query?
Just asking to make sure, in case there's a better method out there to do my queries more efficiently.

If you want all the values in one query, you will need a way to distinguish the results from each other. Thus you need to select the id column as well. For ease of processing, you can also ORDER BY id <> 1 (which will be 0 for id=1, 1 otherwise), which will give you all the results for id = 1 first, followed by all the results for id <> 1:
SELECT id, my_column
FROM my_table
ORDER BY id <> 1
In terms of using this in PHP, you could do something like (assuming mysqli with a connection $conn):
$id_to_find = 4;
$last_id = 0;
$sql = "SELECT id, my_column FROM my_table ORDER BY id <> $id_to_find";
$result = $conn->query($sql) or die($conn->error);
while ($row = $result->fetch_assoc()) {
if ($row['id'] == $id_to_find) {
// do something
}
else {
if ($last_id == $id_to_find) {
// output distinguishing line
}
// do something else
}
$last_id = $row['id'];
}
Because of the ORDER BY clause, this would do all the somethings before all the something elses which would have the same effect as performing the two queries sequentially.

If you want all values from my_table, you may want to try just the
SELECT my_column FROM my_table
This will give all the values where id = 1 and id <> 1.

Related

How to store a PHP variable from a SQL table INT camp

This is my table:
All I want to do is to obtain the '75' int value from the 'expquim' column to later addition that number into another (75+25) and do an UPDATE to that camp (now it is 100).
Foremost, there are dozens of ways to accomplish what you want to do. If you're querying the table, iterating over results and doing some conditional checks, the following will work for you. This is pseudo code... Check out the function names and what parameters they require. $db is your mysqli connection string. Obviously replace tablename with the name of your table. The query is designed to only select values that are equal to 75. Modify the query to obtain whatever results you want to update.
This should get you close to where you want to be.
$query = "SELECT * FROM tablename WHERE idus='1'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['expquim'] == 75){
$query2 = "UPDATE tablename SET expquim='".$row['expquim']+25."' WHERE idus='".$row['idus']."' LIMIT 1 ";
$result2 = mysqli_query($db,$query2);
}
}

multi sql select then insert

i have a total of 6 different tables that i select from then insert to a table before i do another select i was wondering if there was a way to skip the insert part and just do a select and combine all table data. the problem with the select and insert then select aproach is it gets really slow when there are about 1k+ records inserted. it takes about 30sec to 1min or more
im trying something like this
$sql = "select 1";
$statement = $conn->query($sql);
$rowset = $statement->fetchAll();
$sql1 = "select 2";
$statement1 = $conn->query($sql1);
$rowset1 = $statement1->fetchAll();
$combine = array_merge($rowset,$rowset1);
foreach ($combine as $key => $part) {
$sort[$key] = strtotime($part['date']);
}
array_multisort($sort, SORT_DESC, $combine);
To me it seems that you are replicating in php what you could do in sql. The above code in sql looks sg like this:
(select 1)
union all
(select 2)
order by date desc
You may have to tweak the order by clause depending on what data you exactly have in the date field. Otherwise, the above sql code should produce the exactly same results as your php code.

Count occurrences of value in row

I have a row in my mySQL database called "status". In that row i got three different values, either "S", "R" or "L".
Whats the easiest way to count and output the number of occurrences of each value with php?
Thanks!
You can get the counts as separate rows with:
SELECT status, COUNT(*) as count
FROM yourTable
GROUP BY status
You can get them in a single row with:
SELECT SUM(status = 'S') AS s, SUM(status = 'L') AS l, SUM(status = 'R') as r
FROM yourTable
After this, you can read a single row of results:
$row = $pdo->fetch(PDO::FETCH_ASSOC);
$s_count = $row['s'];
$l_count = $row['l'];
$r_count = $row['r'];
It's hard to tell without a full look at your database, but the basic structure is this (assuming you have another row called id)
Edit: to demonstrate in php
$dbc = new mysqli($host, $username, $password, $dbname);
$query = $dbc->query("select id, count(status) as status_count
where status = 'S'
group by id");
$query->fetch_assoc();
$row = $query->fetch_assoc();
echo $row['status_count'];
OR if you have more than one row do it like this:
while ($row = $query->fetch_assoc()) {
echo $row['status_count'];
}
The better way its to use a mysql query using COUNT
You can count all the raws
SELECT COUNT(*) FROM DATABASE
or one raw
SELECT COUNT(colum_name) FROM DATABASE
To be more easy you can give it a variable name like this:
SELECT COUNT (Colum_name) as name FROM DATABASE
So an example,after you connect to your database
Use this:
$ query = mysql_query ('SELECT COUNT (R) as R FROM status');
$ result = mysql_fetch_array ($ query);
Echo $ result ['R']
Hope this will help you !

Insert into one table if no record exists in another table

How can I club this two queries into one? Insert a record if a record does not exist in another table. I tried googling but I have only found solutions using joins, not in but here I guess there is no relation between this two tables. can I still insert into it with a single query
$res = mysqli_query($con,"SELECT 1 FROM bicds WHERE (bid = $pid] AND uid = $eid)
OR (bid = $eid AND uid = $pid) LIMIT 1");
if(mysqli_num_rows($res) == 0){
mysqli_query($con,"Insert into t1 (pid,ust) values ($pid,$ust)");
}
Any help is greatly appreciated. Thanks
You can do this using insert . . . select:
Insert into t1(pid, ust)
select $pid, $ust
from dual
where not exists (select 1 from bicds where bid = $pid AND uid = $eid);
This allows you to include a where clause in the insert.
You can try using CASE condition in query along with a check on number of rows as the condition.
select (count *) from FROM bicds WHERE (bid = $pid] AND uid = $eid)
OR (bid = $eid AND uid = $pid) LIMIT 1")
This will be 0 or NULL if table doesn't exist.

MySQL add values from all rows

How would I add up all the integers in the column, _view_count_, on my table, 'videos', then echo it to display on my page?
For example:
if row id 1 has view_count == 328
and
if row id 2 has view_count == 271
How would I make MySQL add those together and echo it out?
You can use MySQL's SUM() and your SQL query would look something similar to:
SELECT SUM(view_count) FROM videos;
To query and echo the value, if you're using mysqli methods in your PHP code, you can use:
$result = $mysqli->query('SELECT SUM(view_count) AS sum FROM videos;');
$row = $result->fetch_assoc($result);
echo $row['sum'];
Assuming you have a $mysqli object defined your code should look like:
$query = "SELECT Sum(view_count) as mySum FROM videos";
$result = $mysqli->query($query);
$row = $result->fetch_assoc($result);
echo $row['mySum'];
SELECT SUM(view_count) FROM videos
Assuming you have a COLUMN id, you can use SUM together with IN, like so:
SELECT SUM(view_count) FROM videos WHERE id in (1,2)

Categories