Select mySQL data with help of other table - php

I'm currently working on a message board which only displays data if values in another table are set.
My 2 tables look like this:
tbsubscribers:
-subID (int)
-msg1 (tinyint)
-msg2 (tinyint)
-msg3 (tinyint)
-email (varchar)
tbmessage
-id (int)
-name (varchar)
-mitteilung (varchar)
-sender (varchar)
-datum (datetime)
The actual messages are in the tbmessage table and to check which messages the user wants to see there is the tbsubscribers table.
Now, I want to display the messages. So if a user subscribed to msg1 and msg2 (so the value of both are 1) it should select all the data from tbmessage which has the name 'msg1' and 'msg2'.
I know how to work with select in mysql but don't know how I could select multiple tables, and especially in this case I'm kind of confused how I would do this.
Any help would be appreciated

A simple join should work:
SELECT * FROM `tbsubscribers` s
RIGHT JOIN `tbmessage` tb ON (
CASE WHEN msg1 = 1 THEN name = 'msg1' END OR
CASE WHEN msg2 = 1 THEN name = 'msg2' END OR
CASE WHEN msg3 = 1 THEN name = 'msg3' END
)
I created a sqlfiddle here, which should demonstrate the functionality you're looking for.
I'm going to make some edits to clarify how you should do this, using both the query above, and another query if need be.
There are a few ways you can do this. Way #1:
<?php
/*
* If you already have username (email) in session,
* then you can do this:
*/
$query = "SELECT m.* FROM `tbsubscribers` s
RIGHT JOIN `tbmessage` m ON (
CASE WHEN msg1 = 1 THEN name = 'msg1' END OR
CASE WHEN msg2 = 1 THEN name = 'msg2' END OR
CASE WHEN msg3 = 1 THEN name = 'msg3' END
)
WHERE email = " . my_escape_string_function($_SESSION['username']);
/*
* If tbsubscribers has a '1' in msg1, then all msg1's are grabbed.
* If tbsubscribers has a '2' in msg2, then all msg2's are grabbed...etc
*/
//Set $rows equal to the result
return $rows;
?>
Way #2:
<?php
/*
* If you already have username (email) in session,
* then you can do this:
*/
$query = "SELECT * FROM `tbsubscribers` s
WHERE email = " . my_escape_string_function($_SESSION['username']);
/*
* Run this query, and fetch the entire userrow, and put into $user
* An alternative could be to just store the entire user array into
* $_SESSION, as you wont have to query the database twice.
*/
$tofetch = array();
for ( $i=1; $i<=3; $i++ )
{
//Let's check msg1, msg2, msg3
if ( $user['msg' . $i] )
{
$tofetch[] = "name = 'msg" . $i . "'";
}
}
/*
* If tbsubscribers has a '1' in msg1, and a '1' in msg2 then the array
* will look like this:
* array(
* 0 => "name = 'msg1'"
* 1 => "name = 'msg2'"
* )
*/
//Throw an exception if all 'msg1', 'msg2', and 'msg3' are all 0 (Otherwise the query will fail)
if ( empty($tofetch) ) {
throw new Exception("You're not subscribed to any messages.");
}
/*
* Now it's a simple query. $tofetch will be imploded, to form a nice
* where statement. Using the example above, it will look like:
* name = 'msg1' OR name = 'msg2'
*/
$query = "SELECT *
FROM `tbmessage`
WHERE " . implode(' OR ', $tofetch);
//Set $rows equal to the result
return $rows;

Related

PHP Query - Exclude if exist in table

orderfood
orderfood_id food_id total_amount
foodcancel
foodcancel_id food_id status
$query = $this->db->query("SELECT * FROM order_food of LEFT JOIN `foodcancel` fc ON of.food_id = fc.food_id WHERE of.orderfood_id = '" . (int)$orderfood_id . "'");
$order_foods = $query->rows;
above is my query, what i wanted is that if there food_id inside foodcancel table , exclude it from rows, possbile to do it ?
For exclude the existing values you could try checking null for corresponding matching value
SELECT *
FROM order_food of
LEFT JOIN foodcancel fc ON of.food_id = fc.food_id
and of.food_id = your_value
WHERE fc.orderfood_id is null
anyway you should not php var in your sql code because in this way you are are risk for sqlinjection for avoid this you should take a look at prepared statement and binding param
It's very possible to do. In my logic. first, you must get all food_id on food_cancel table. Then save it into variabel and use it when you show orderFood table with adding NOT IN condition.
I've write code for you,
<?php
// Get Food Id From Cancel
$orderCancel = mysqli_query($mysqli, "SELECT * FROM `foodcancel`");
$cancelId = "";
while ($cancel = mysqli_fetch_array($orderCancel)) {
$cancelId .= $cancel["food_id"].",";
};
$cancelId = substr($cancelId, 0, -1);
// Put Food Id on Cancel Table into NOT IN Condition Database
$orderFood = mysqli_query($mysqli, "SELECT * FROM `orderfood` WHERE food_id NOT IN ($cancelId)");
while ($order = mysqli_fetch_assoc($orderFood)) {
$food[] = $order;
};
echo json_encode($food);
?>

Select data from the database before or after a defined value

I am having problems achieving the query to select data from a table in the db after a defined value has been met.
My code to do this is:
$fi = 'first_segment'
$im = popo.jpg
$sqls = "SELECT * FROM $fi,news_pictures
WHERE $fi.pi_id = news_pictures.pi_id
AND news_pictures.i_name = '$im'
GROUP BY news_pictures.id DESC";
I wasn't able to achieve the result with that query.
Basically, I want the query to confirm if news_pictures.i_name = '$im' and if true, return starts from the value of $im followed by other data in the table depending on news_pictures.id DESC.
The sample data and output:
Table news_pictures:
id i_name
-- ------
1 coco.jpg
2 lolo.jpg
3 popo.jpg
4 dodo.jpg
Since $im = popo.jpg, I want my query to display all values starting from popo.jpg with id DESC, i.e. popo.jpg, lolo.jpg, coco.jpg.
I got to solve the question with the help of a friend.
$fsqls = "SELECT * FROM $fi,news_pictures WHERE $fi.pi_id = news_pictures.pi_id AND news_pictures.i_name = '$im' GROUP BY news_pictures.id";
$rres = mysqli_query($connection, $fsqls) or print(mysqli_error($connection));
while($row = mysqli_fetch_assoc($rres))
{
$rnm = $row["id"];
}
$sqls = "SELECT * FROM news_pictures WHERE news_pictures.id <= $rnm ORDER BY news_pictures.id DESC";

mysql select multiple values from array match

I have an array lets say: Array ( [0] => 9 [1] => 7 [2] => 8 )
I want to SELECT from a table (users) all phone numbers where userID matches one from the array (if there is a phone number listed).
I want to do this without selecting all of the users from the database and only those that match that of the array and with actual phone numbers, should I do this in a loop?
Typically when I am doing an UPDATE, I do them within a foreach loop. Like so:
foreach($userArr as $user) {
$pid = $user;
if(!$statement->execute()) {
throw new Exception($statement->error, $statement->errno);
}
}
$statement->close();
Can we do SELECT like that as well?
Thanks in advance for any advice.
If you want to select all these users, just do the follow:
$idList = implode(',', $yourArray);
$sql = "SELECT * FROM users WHERE id IN($idList)";
// execute this $sql query
Try this:
<?php
$array = array(9, 7, 8);
$query = "SELECT * FROM mytable WHERE id = ";
$condition = implode(' OR id = ', $array);
$query .= $condition;
echo $query;
?>
Output:
SELECT * FROM mytable WHERE id = 9 OR id = 7 OR id = 8
You should do the following:
Build a string to express the userid seperated by comma. - Loop will be needed. i.e id1, id2, id3
Build the query string to search for them.
Example:
SELECT * FROM `Users` WHERE id IN (id1, id2, id3)

Update a mysql table based on another. Complicated query

Short about my tables: I have 2 tables: content, users
content structure is something like:
id | title | cpc | user | active
users is:
id | user | monetos
Idea - I want to select contet.* rows which have content.active = 1 (n). Having this data, SELECT users.monetos WHERE users.id=content.user from previous query.
And now, by maximum (n) steps i decrement users.monetos value by content.cpc value
and on the moment when *users.monetos=0 or less than 0, i want to update content and SET active='0'*
By words, i want like to share users.monetos amount to each content entry (content.cpc for each). And there's no more users.monetos make the current content
entry inactive. And do this vor every content.user
What i'he done at this moment is shown below. I now it looks really bad, but i already don't know what to do. Count on you guys. Thank you.
$kak2 = array();
$rs16 = $connector->query("SELECT user FROM content WHERE active='1'");
while($rw16 = $connector->fetchArray($rs16))
{
$users_ids[] = $rw16['user'];
}
$user_info2 = $connector->fetchArray("SELECT monetos,id FROM users WHERE id IN (".implode(',',$users_ids).")");
while($user_info = $connector->fetchArray($user_info2))
{
$current_entry_info2 = $connector->query("SELECT cpc,id FROM content WHERE user='$user_info[id]' ORDER BY date DESC");
while ($current_entry_info = $connector->fetchArray($current_entry_info2))
{
$user_info['monetos']= $user_info['monetos'] - $current_entry_info['cpc'];
if($user_info['monetos'] = 0)
{
$updt = $connector->query("UPDATE content SET active='0' WHERE id='$current_entry_info[id]' LIMIT 1");
}
}
}
I think i have got the idea of what you are trying to do so have contructed a small code snippit which i think should do what you are after.
note this is untested code
/** get the cost of all content for all users **/
$query = "select b.id, sum(a.cpc) as cpc from content a
join users b on a.user= b.id
group by b.id where a.active = 1"
/** cycle each user **/
foreach($rows = $connector->fetchArray($query) as $row ) {
$menotos = $row['cpc'];
$query = "select id, cpc from content where user={$row['id']}"
/** cycle each users content **/
foreach($contents = $connector->fetchArray($query) as $content) {
$menotos -= $content['cpc'];
if($menotos <= 0) {
$disable[] = $content['id'];
}
}
if( isset($disable) ) {
$connector->query("update content set active=0 where id in(" . implode(',', $disable) . ")";
}
}

How make dynamic php page for all queries in table

I'm trying to retrieve dynamic query PHP pages. First page passing values of city or id next page by post method.
I know here sql injection can done.
but i m using in it on private network and every user session is tracked.
and table1 is protected.
Table looks like this:
TABLE1
-----------------------------------------------------
1 select * from tablename1 where ID = $id
2 select * from tablename1 where city = $city
2 select * from tablename1 where ID = $id and city = $city
-----------------------------------------------------
Now I run page contain code:
$id = $_POST["id"];
$city= $_POST["city"];
$tabledata = mysql_query("SELECT * FROM table1 ");
$a=mysql_fetch_row($tabledata );
$query_table=$a['1']; // retrieve sql query from table1 which stored in 2nd column
echo " $query_table"; // display query
$result = mysql_query($query_table);
while ($field = mysql_fetch_row( $result) )
{
echo "<td> $field[1] </td>";
}
Now, the problem is that I can't get results. $result is empty?
How pass $city or $id value to query?
But if I remove WHEREcondition from TABKE1 then it works well. So, how can I make for WHERE condition to pass parameters?
how can i do this . any other option here to call stored query on 1 table and process it on other page and oher table
The query in table1 should be like this
-----------------------------------------------------
1 select * from tablename1 where ID = '".$id."'
2 select * from tablename1 where city = '".$city."'
3 select * from tablename1 where ID = '".$id."' and city = '".$city."'
-----------------------------------------------------
and proceed further with your coding and it will show you the result.
OPTION 2:
Table 1:
-----------------------------------------------------
1 select * from tablename1 where ID =
2 select * from tablename1 where city =
-----------------------------------------------------
and change in php code like this
$query_table=$a['1']." '".$id."'" ;
or
$query_table=$a['2']." '".$city."'" ;
OPTION 3:
Table 1:
-----------------------------------------------------
1 select * from tablename1
-----------------------------------------------------
and change in php code like this
$query_table=$a['1']." where ID = '".$id."'" ;
or
$query_table=$a['1']." where ID = '".$id."' AND city = '".$city."' " ;
If you want the result with ID or City
mysql_query("SELECT * FROM table1 WHERE ID = '$id' OR city = '$city'");
and If you want with both mandatory
mysql_query("SELECT * FROM table1 WHERE ID = '$id' AND city = '$city'");

Categories