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

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')

Related

i want to select a randomly data using php

I need help in selecting a random data from the table
Let's suppose There are 10 columns in my table but i want that if I hit the query sometime it will bring all data and sometime it will bring data only from 1 column and some time from the no 1 and no 2 column
How can I achieve this?
Thanks in advance
function selectAllInventoriesINGroup($conn,$groupname,$import_id)
{
$cgstSgst = explode('-', $groupname);
$sql = "SELECT * FROM stockitems WHERE generalid = '$import_id' AND cgst = '$cgstSgst[0]' AND sgst = '$cgstSgst[1]' ORDER BY RAND()";
$result = $conn->query($sql);
$jsonxx = mysqli_fetch_all ($result, MYSQLI_ASSOC);
return $jsonxx ;
}
I have tested this but it fetch the all the data from the database
<?php
$sql = "SELECT * FROM stockitems WHERE generalid = '$import_id' AND cgst = '$cgstSgst[0]' AND sgst = '$cgstSgst[1]' ORDER BY RAND()";
?>

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);
}

Query not displaying distinct values using 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'];
}}}

How select random column value from Mysql database using PHP

I'm trying to fetch random column from database using Rand() function.
It's returning random value but many time it is returning duplicate.
This is what my database table look like.
Column
Type
Null
Default
no
int(30)
No
postid
varchar(100)
Yes
NULL
byuser
varchar(32)
Yes
NULL
likeslimit
int(30)
No
createdon
date
No
And this is what my PHP code is.
$query = mysqli_query(
$mysql,
"SELECT postid FROM history ORDER BY Rand() LIMIT 1"
);
if (mysqli_num_rows($query) == 1) {
while ($row = mysqli_fetch_assoc($query)) {
echo $row['postid'];
}
}
I want it to always return random never the same till the end of data reached.
Don't use loop and condition you want only 1 limit try this
$query = mysqli_query(
$mysql,
"SELECT postid FROM history ORDER BY Rand() LIMIT 1"
);
$row = mysqli_fetch_assoc($query)
echo $row['postid'];
This is the way RAND in mysql works and will repeat the results from time to time. But you can achieve such functionality by using mysql with php.
$query = mysqli_query($mysql, "SELECT postid FROM cacheTable WHERE 1 ORDER BY RAND() LIMIT 1");
$row = mysqli_fetch_assoc($query);
$foundId = (int)$row['postid'];
if((int) $foundId === 0) { // NO records left in cacheTable then fill it up again
mysqli_query($mysql, "INSERT INTO cacheTable (postid) SELECT postid FROM history");
$query = mysqli_query($mysql, "SELECT postid FROM cacheTable WHERE 1 ORDER BY RAND() LIMIT 1");
$row = mysqli_fetch_assoc($query);
$foundId = (int) $row['postid'];
}
mysqli_query($mysql, "DELETE FROM cacheTable WHERE postid=".$foundId); // DELETE the record
$query = mysqli_query($mysql, "SELECT * FROM history WHERE postid=".$foundId);
$result = mysqli_fetch_assoc($query);
cacheTable will have only one column - ID (primary key) which will hold the corresponding ID (primary key) from history. cacheTable structure:
|------
|Column|Type|Null|Default
|------
|postid|varchar(100)|Yes|NULL
|-----
cacheTable will fill with all the ids from history table (it will be done once the cacheTable is empty). You will select rand result from the cacheTable and you will delete it then so it will not appear in the next selects. When we are out of records in cache table it will populate again.
NB: this approach has one major drawback - when you have new entries in history table they won't be available in cache table until it is empty and filled again.
This is the code Samir Nabil Suggested :
session_start();
$_SESSION['dupes'] = array();
$query = mysqli_query(
$mysql,
"SELECT postid FROM history ORDER BY Rand() LIMIT 1"
);
if (mysqli_num_rows($query) == 1) {
while ($row = mysqli_fetch_assoc($query)) {
if (!in_array($row['postid'], $_SESSION['dupes'])) {
echo $row['postid'];
$_SESSION['dupes'][] = $row['postid'];
}
}
}

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'];
}
}
}

Categories