Query not displaying distinct values using php - php

I am trying to make a dropdown menu of cat_id which is present in table of partner. Currently I am getting duplicate values of cat_id. I want to get it only once. Please note partner id is drived from another table and they are more than one. Here is my code.
$query = $mysqli->query("SELECT * FROM favourites WHERE user_id='$userid'");
if($query->num_rows != 0){
while ($rows = $query->fetch_assoc())
{
$partnerid = $rows['part_id'];
$query = $mysqli->query("SELECT DISTINCT cat_id FROM partner WHERE
partner_id=$partnerid");
while ($rows = $query->fetch_assoc())
{
$cat_id = $rows['cat_id'];
}}}

Related

MySQL: Get all Columns of Table starting with name "ctr_" and value 1

I have a country restriction on products in my shop and a slow query to select all country-columns with a value of 1 from the table product.
I select all active countries in my shop:
$ids = select id from country where active = 1;
Then I select all countries, which are active in a product:
foreach $ids as $id { select ctr_{$id} from product where ctr_{$id} = 1;
Is there a faster way to get the columns starting with ctr_* and which value is equal to 1?
Try the following
// first get the columns
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='product' AND COLUMN_NAME LIKE 'ctr_%'";
$result = mysqli_query($conn, $query) or trigger_error(mysqli_error($conn),E_USER_ERROR);
$cols = Array();
while($row = mysqli_fetch_row($result)) $cols[] = $row[0];
// then build the query
if(count($cols))
{
$query = 'SELECT '.implode(',', $cols).' FROM product WHERE 1 IN ('.implode(',',$cols).')';
$result = mysqli_query($conn, $query) or trigger_error(mysqli_error($conn), E_USER_ERROR);
while($row = mysqli_fetch_assoc($conn,$result))
{
// do something with the row
// ....
}
}

get required result in sql

i have a sql database having two columns
1. id and 2. parent_id
i want to select all ids where parent_id=1 [let the results saved in X array] then,
select all the ids where parent_id in X[] [let the results saved in Y array] then... do the same upto 7 levels at last i want to sum all levels and get that sum in a variable name "number"
what i tried:
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id = ".$parent[id];
$result = mysqli_query($con, $sql);
$lv1 = mysqli_fetch_array($result);
then again
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id in ($lv1)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
and so on.... it may give me required result but it is too much code...
i want to the same by using a loop or something else... to shorten the code.
Your first query gets count(id) and then second query uses it to get results. It seems you have many flaws in your requirement to begin with.
However, for your question you can use sub-query like following
$sql = "SELECT count(id) as leadersearch
FROM `$database`.`$mem`
WHERE parent_id in (
SELECT id FROM `$database`.`$mem` where parent_id = ".$parent['id']."
)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
If you have many level nesting and you want to search records like this then you can consider functions:
function getLeader($parent_id){
$results = [];
$sql = "SELECT id as leadersearch FROM `$database`.`$mem` where parent_id in (".$parent_id.")";
$result = mysqli_query($con, $sql);
foreach($row = mysqli_fetch_array($result)){
$results[] = $row['id'];
}
return $results;
}
$leaders = [];
$ids = getLeader($parent['id']);
foreach($ids as $id){
$leaders[$id] = getLeader($id);
}

php - sql select "where" equals to a couple of variables?

I am parsing 3 variables from JSON link, each of variable consist of the name of a cinema theater:
$cinema1
$cinema2
$cinema3
After, I need to select an ids of all 3 cinemas from the table, then using that ids I need to look for the table "movietimings" to see if there is movies are playing today, if there is a movie playing in that cinemas today, then I need to go for "movie" table and show all information about that movie.
So, this is what have been accomplished:
$sql2 = "SELECT DISTINCT * FROM cinema WHERE cinemaname = '$cinema1' AND cinemaname='$cinema2' AND cinemaname='$cinema3' ";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
$cinemaid2 = $row2['id'];// I have received a cinema id
//getting the main id, since the id I just got is a branch of the main cinema, so the main id that is associated with movie timings is down below
$sql5 = "SELECT DISTINCT * FROM cinemas WHERE cinemaname = '$cinemaid2'";
$result5 = $conn->query($sql5);
if ($result5->num_rows > 0) {
// output data of each row
while($row5 = $result5->fetch_assoc()) {
$cinemaid = $row5['id'];//received main id required
$today = date("m/d/Y");//getting todays date
//now trying to find if a movie today playing
$sql3 = "SELECT * FROM moviecinemashowsassociation WHERE cinemaid LIKE '$cinemaid' AND showdate LIKE '$today'";
$result3 = $conn->query($sql3);
if ($result3->num_rows > 0) {
// output data of each row
while($row3 = $result3->fetch_assoc()) {
$movieid = $row3['movieid'];// selected a movie id played today
//selecting information about movie
$sql4 = "SELECT * FROM movie WHERE id='$movieid'";
$result4 = $conn->query($sql4);
if ($result4->num_rows > 0) {
// output data of each row
while($row4 = $result4->fetch_assoc()) {
The problem is that I have 3 different cinemas which should go through one loop.
You are looking for a OR condition instead of AND condition since the cinemaname can't hold multiple value at same point of time and thus it would be either of the values specified
WHERE cinemaname = '$cinema1' OR cinemaname = '$cinema2' OR cinemaname = '$cinema3'
(OR) Use a IN operator
WHERE cinemaname IN ('$cinema1' ,'$cinema2' , '$cinema3')

How can I show rows from one table that aren't in another table?

I have two tables in a database, one of them is a list of 'buildings' you could create. The other is a list of buildings that have been built by users.
On one page, (cityproduction.php), it displays a list of 'buildings' you can build.
I want it to display the buildings that you can build, that you haven't already built.
Here is my code:
$sql = "SELECT * FROM [The list of built buildings] WHERE building_owner = '$user'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$variable = $row["building_name"];
}
(...)
$sql = "SELECT * FROM [The list of ALL buildings] WHERE name != '$variable' ORDER BY id asc";
$result = mysqli_query($database,$sql) or die(mysqli_error($database));
while($rws = mysqli_fetch_array($result)){
echo $rws["name"]; (etc.)
What this is doing is only not-showing one of the buildings that the user has built, not all of them.
Without seeing the real table names or the schema it is tricky to answer accurately but you could try something along these lines:
SELECT * FROM `all_buildings`
WHERE `id` not in (
select `building_id` from `built_buildings` where `building_owner` = '$user'
)
ORDER BY `id` asc;
Another translation of your question into SQL (besides NOT IN) results in a Correlated Subquery:
SELECT * FROM `all_buildings` AS a
WHERE NOT EXISTS
(
select * from `built_buildings` AS b
where a.`id` = b.`building_id` -- Outer Select correlated to Inner
and b.`building_owner` = '$user'
)
ORDER BY `id` asc;
The main advantage over NOT IN: it's using only two-valued-logic (NULL is ignored = false) while NOT IN uses three-valued-logic (comparison to NULL returns unknown which might no return what you expect)
Why are you using while after the first query, it suppose to be a list or just a single value? because if you use $variable in your second query it will only have the value of the last value of the list you are getting
if ($result->num_rows > 0) {
$variable = array();
while($row = $result->fetch_assoc()) {
$variable[] = $row["building_name"];
}
Second query example:
foreach($variable as $building) {
$sql = "SELECT * FROM [The list of ALL buildings] WHERE name != '$building' ORDER BY id asc";
$result = mysqli_query($database,$sql) or die(mysqli_error($database));
$result = mysqli_fetch_assoc($result);
echo $result["name"];
}
Assuming both of your tables have some sort of id column to relate them, with this query:
SELECT building_name, building_owner FROM
test.all_buildings a
LEFT JOIN test.built_buildings b ON a.id = b.building_id AND b.building_owner = ?
ORDER BY building_owner DESC, building_name;
(where ? is the user), you can select all the buildings, first the ones that have been built, followed by the ones that haven't, in one query. If your tables don't have id's like that, you can join them on name instead; it should work as long as the names are distinct.
Then as you fetch the rows, you can sort them into "built" or "not built" by checking if the row has a building_owner.
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row['building_owner']) {
$built[] = $row['building_name'];
} else {
$not_built = $row['building_name'];
}
}
}

Displaying based on Results in Mysql Query

I have an orders table in mysql and in that for some orders I set particular order status like 'review'.
I want to setup a way if any order placed by a particular customer(first and last name) for whom i have previously set order status as 'review' to display a warning in the list.
$sql = "select * from order where firstname = ".$firstname." AND lastname = ".$lastname." AND order_status = 'review';";
$SQLresult = mysql_query("$sql", $DBcon_MySQL);
while($row = mysql_fetch_array($SQLresult)) {
foreach($row as $row){
$result = "warning!";
echo $result;
}
}
The above code does not display anything. please let me know how to fix this.
[EDIT After Applying Answer]
This is how i am using it.
<td width="200">
<?
$sql = "select * from cust_order where firstname = '$firstname' AND lastname = '$lastname' AND order_status = 'review'";
$SQLResult = mysql_query("$sql", $DBcon_MySQL);
while($row = mysql_fetch_array($SQLResult )) {
//$result;
foreach($row as $row ){
//$result="";
$result = "Warning!";
}
?>
<p><? echo $result;?></p>
<?} ?>
</td>
How should i insert a check that it should display warning only once No matter how many orders from single customer are marked as review, display warning only once?
try this,
$sql = "SELECT
*
FROM
`order`
WHERE
firstname = '$firstname' AND lastname = '$lastname' AND
order_status = 'review' LIMIT 1";
$SQLresult = mysql_query($sql, $DBcon_MySQL);
while($row = mysql_fetch_array($SQLresult)) {
foreach($row as $row){
$result = "warning!";
echo $result;
}
}
Please be informed that mysql functions are deprecated and not recommended. USE MySQLi or PDO instead. have a reference from following queries.
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php

Categories