Switch Statement based on if variables in two tables match - php

So I have a switch statement that I want to display one form or another based on if the id from one table has the matching foreign key in another table.
So far what I have tried is nesting one while statement into another which isn't working.
$subresult = mysqli_query($con,"SELECT * FROM tags GROUP BY tag");
$subresult2 = mysqli_query($con,"SELECT * FROM tag_subscribe WHERE uid = $uid");
while ($row = mysqli_fetch_array($subresult)) {
$tid = $row['tid'];
while ($row2 = mysqli_fetch_array($subresult2)) {
$tid2 = $row2['tid'];
}
if ($tid2 == $tid) {
$subbedup = 'yes';
} else {
$subbedup = 'no';
}
switch ($subbedup) {
case ('yes'):
echo "alternate html form goes here because $tid2 == $tid";
break;
case ('no'):
echo "html form goes here";
break;
}
}
So when this code is run, it only returns switch "no" except it will return one switch "yes" which just happens to be the last record of the second table that contains the foreign key. When I think about it, that makes sense as it will just keep running through this loop until it runs out of records in the table. So I spent about six minutes getting to this point and I have spent the last 6 hours trying to get it to work correctly without any luck.
So once again, fine people at SO, save me! Please and Thank you :)
So my question is: How would this be done correctly?

I'm not exactly sure of your database structure, so I'll improvise.
Given these sample tables and columns:
tags
id name
tag_subscriptions
user_id tag_id
The query below will loop through all tags. Each tag includes a subscribed column set to either "yes" or "no", depending on whether the current user is subscribed to that particular tag.
$sql="SELECT t.`id`, t.`name`, IF (ISNULL(ts.`tag_id`),'no','yes') AS `subscribed`
FROM `tags` t
LEFT JOIN `tag_subscriptions` ts ON (ts.`user_id`=$uid AND ts.`tag_id`=t.`id`)
WHERE 1;"
Then loop through all tags:
$q=mysql_query($sql) or die(mysql_error());
while ($row=mysql_fetch_assoc($q)) {
switch ($row['subscribed']) {
case 'yes'
// user is subscribed to this tag
break;
default:
// user is not subscribed to this tag
}
}
I think (hope) this is closer to what you're looking for.
http://sqlfiddle.com/#!2/58684/1/0

Sorry for using PDO as thats what i know, you can convert the idea to MYSQLi im sure.
$db = new PDO($hostname,$username,$password);
$arraySubTags = array();
$query = "SELECT tagID FROM tag_subscribe WHERE uid = :uid";
$statement = $db->prepare($query);
$statement->bindValue(':uid', $uid);
$statement->execute();
$subscribedTags = $statement->fetchAll(PDO::FETCH_ASSOC); //or loop with a while using fetch()
$statement->closeCursor();
foreach($subscribedTags as $sTag)
{
array_push($arraySubTags,$sTag);
}
$query = "SELECT * FROM tags GROUP BY tag";
$statement = $db->prepare($query);
$statement->execute();
$allTags = $statement->fetchAll(PDO::FETCH_ASSOC); //or loop with a while using fetch()
$statement->closeCursor();
foreach($allTags as $tag)
{
if(in_array($tag['tagID'], $arraySubTags))
{
echo "person is subscribed";
}else{ echo "person not subscribed";}
}

This code just checks whether the last tag checked is subscribed to - to check for each one you need to move the switch statement into the outer while loop, after the if..else bit that sets the $subbedup variable for the current tag.
Or you could make $subbedup an array, indexed by the tag id, if you need to keep the switch separate for some reason.

Related

How to check all values present in the column 'pincode'?

This code only reads the first value present in the column. If the value posted in the html form matches the first value, it inserts into the database. But I want to check all the values in the column and then take the respective actions.
For example, if i give input for 'ppincode' and 'dpincode' as 400001, it accepts. but if i gave 400002, 400003,..... it displays the alert even if those value are present in the database
DATABASE:
pincode <== column_name
400001 <== value
400002
400003
400004
...
also i tried this
$query = "SELECT * FROM pincodes";
$result = mysqli_query($db, $query);
$pincodearray = array();
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)){
$pincodearray[] = $row;
}
}
If I understand well - you want to compare value from POST request with all retrieved records saved in DB and if it matches - perform action.
If so, I would recommend using for(each) loop. Example:
if( !empty($row){
foreach( $row as $key ){
if($key['pincode'] == $ppincode && $key['pincode'] == $dpincode){
// your action goes here
}
}
}
Additional tip: use prepared statements :)
SELECT count(*) FROM table WHERE ppincode=ppincode AND bpincode=bpincode
if this return 0 then insert or else show alert.

Displaying results from SQL query in PHP in a table

I am having some trouble with displaying some SQL query results.
Goal: I want to display the Helper 'name' in the table that is being generated if there is a helper signed up in the 'signup' table for that event 'eid' (event id).. If (1)there is no helper then display 'waiting for help', (2) there is a helper then display 'name -- awaiting approval..' and (3) else just display the name of helper..
Tried running the SQL query in phpMyAdmin with hard coded values and I get the results that I want so I know it is not my query. Have a suspicion that it is just the print out of the info into the table that is wrong somewhere. The table will display the data up until the ZIP from the address and then the next column which is the 'Helper' column does not display anything at all. So it makes me think I have a simple typo somewhere based on my if() statement logic BUT also find it interesting also that when I do the line:
echo "testing method -> ".getHelperIdOrName(2, 80)."<br>";
I cant get the table to print out at all. Not sure if this is related to my exact issue but it seems it could be. After I put this function in stuff stopped working so it seems like it could be culprit. The return of the function should either return an ID (int), a name "string", or just a generic value X (string)..
Any and all help is appreciated!
function getHelperIdOrName($x, $eid){
//Get the helper name first
$helperName = "";
$helperId = 0;
$sql = "SELECT id, first FROM users WHERE id IN (SELECT helper FROM signup WHERE gner = '".$userId."' AND eid = '".$eid."')";
$result = mysqli_query($db,$sql);
$row = $result->fetch_assoc();
if ($x == 2){
$helperName = $row["first"];
return $helperName;
}
else if ($x == 1){
$helperId = $row["id"];
return $helperId;
}
else {
return "X";
}
}
echo "testing method -> ".getHelperIdOrName(2, 80)."<br>";
//look for calendar and/or business approved events (approved=1) to display on page
$sql = "SELECT s.gner, s.helper, s.eid, s.approved, e.name, e.date, e.summary, e.street, e.city, e.state, e.zip
FROM signup s
INNER JOIN events e ON e.id = s.eid
INNER JOIN users u ON u.id = s.gner
WHERE s.gner = '".$userId."'";
$result = mysqli_query($db,$sql);
echo "<h3 class=\"text-center\">Events I'm Going To</h3>";
echo "<table class=\"table table-hover\"><tr><th>Event Name</th><th>Date</th><th>Summary</th><th>Location</th><th>Helper</th><th>Remove</th></tr>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["name"]."</td><td>".$row["date"]."</td><td>".$row["summary"]."</td><td>".$row["street"].", "
.$row["city"].", ".$row["state"]." ".$row["zip"]."</td>";
$tmp_eid = $row["eid"];
if (getHelperIdOrName(2, $temp_eid) == "X"){
echo "<td>Waiting for help..</td>";
}
else if ($row["approved"] == 0){
echo "<td>".getHelperIdOrName(2, $temp_eid)." -- Awaiting Approval (see below)</td>";
}
else {
echo "<td>".getHelperIdOrName(2, $temp_eid)."</td>";
}
echo "<td><form method=\"post\" action=\"remove.php\">
<button type=\"submit\" name=\"remove\" value=\"".$row["eid"]."\">Not Going</button></form></td></table>";
}
}
else echo "</table><br><p class=\"text-center\">You are not signed up for any events. Click here to sign up for events near you!</p>";
Thanks for that Jeff. The issue was that inside of the function it indeed did not know what $userId was even though I had the include statement at the top of my php file. I had to add this line into my function at the top..
global $db; //is part of my db my connection info in my config.php file
and then I also passed the $userId to the function as a parameter
these lines are what I used to help me see the errors:
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
i also had some ending < /table > tags inside some if logic so that fixed the funky displays I was getting (2nd row of table being outside of the table)

Trying to get a page to populate data from a database

I'm trying to write a script that gets data from a sql server based on the id of the entry in my data base. when I try to access the page using the link with the id of the entry it returns as if it does not recognize the id. Below is the php code :
<?php
require('includes/config.inc.php');
require_once(MYSQL);
$aid = FALSE;
if (isset($_GET['aid']) && filter_var($_GET['aid'], FILTER_VALIDATE_INT, array('min_range' => 1)) ) {
$aid = $_GET['aid'];
$q = "SELECT aircraft_id, aircraft_name AS name, aircraft_type AS type, tail_number AS tn FROM aircraft USING(aircraft_id) WHERE aircraft_id = $aid";
$r = mysqli_query($dbc, $q);
if (!(mysqli_num_rows($r) > 0)) {
$aid = FALSE;
}
}// end isset tid
if ($aid) {
while ($acdata = mysqli_fetch_array($r, MYSQLI_ASSOC)){
echo'<h2>'. $acdata['tail_number'] .'</h2>';
}
} else {
echo '<p>This pages was accessed in error.</p>';
}
?>
Any hints?
Try to var_dump($q); before $r = mysqli_query($dbc, $q); to inspect your query and then just execute it through phphmyadmin or in MySQL server terminal directly and see what does it return.
Update:
Use var_dump($q);die(); to stop script from executing after dumping.
You are using a field alias in your query, so you must use that in your echo to:
echo'<h2>'. $acdata['tn'] .'</h2>';
Get rid of the USING(aircraft_id), it causes an error and your query doesn't execute.
"SELECT aircraft_id, aircraft_name AS name, aircraft_type AS type, tail_number AS tn FROM aircraft WHERE aircraft_id = $aid"
I guess it's a leftover from a previous version of the query? Using (id) is a shortcut for
FROM
foo
INNER JOIN bar ON foo.id = bar.id
It can be used when the tables to be joined are joined on columns which have the same name. Just shorter to write.
Since you are not joining you have to remove it.

PHP Function Dependent on presence of MySQL data entry

I code a weekly trivia program for one of my clients through facebook.
I have a bit of code commented out where we display the winner when we need to. Currently I just remove the comment brackets and update when it's time to display. I'm trying to make this so someone non-savvy can handle updates so I've moved my code into an include:
winner-display.php
I am trying to write a function so that if the winner is set in MySQL, it includes the file in-line, and if the winner field is empty in the database, it does not.
Here is what I have so far, any ideas?
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != 'null') {
include('../includes/winner-display.php');
} else {
}
?>
Ok, thanks for helping guys, got it to work as:
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
foreach ($row as $field) {
if ($field != null) {
include('../includes/winner-display.php');
}
}
}
?>
You can definitely put an include within an if. That solution that you posted should work as you would like it to, although I personally would have used a function instead of a completely separate file to include (although that is personal preference).
All you have to do to make it work is remove the quotes around 'null'.
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = $target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != null) {
include('../includes/winner-display.php');
}
?>
Keep in mind that if your query returns more than one row, only the last row will be retained. I don't know if that is the functionality you want (in which case, there are some changes you could make, just ask me to edit my answer), but I didn't change that.

php query does not retrieve any data?

well, i wanna pull out some data from a mysql view, but the wuery dos not seem to retrieve anything ( even though the view has data in it).
here is the code i've been "playing" with ( i'm using adodb for php)
$get_teachers=$db->Execute("select * from lecturer ");
//$array=array();
//fill array with teacher for each lesson
for($j=0;$j<$get_teachers->fetchrow();++$j){
/*$row2 = $get_lessons->fetchrow();
$row3=$row2[0];
$teach=array(array());
//array_push($teach, $row3);
$teach[$j]=mysql_fetch_array( $get_teachers, TYPE );
//echo $row3;*/
$row = $get_teachers->fetchrow();
//$name=$row[0]+" "+$row[0]+"/n";
//array_push($teach, $row1);
echo $row[0]; echo " ";echo $row[1]." ";
//$db->debug = true;
}
if i try something like "select name,surname from users", the query partially works . By partially i mean , while there are 2 users in the database, the loop only prints the last user.
the original query i wanted to execute was this
$get_teachers=$db->Execute("select surname,name from users,assigned_to,lessons
where users.UID=assigned_to.UID and lessons.LID=assigned_to.LID and
lessons.term='".$_GET['term']."'");
but because it didnt seem to do anything i tried with a view ( when you execute this in the phpmyadmin it works fine(by replacing the GET part with a number from 1 to 7 )
the tables in case you wonder are: users,assigned_to and lessons. ( assigned_to is a table connecting each user to a lesson he teaches by containing UID=userid and LID=lessonid ). What i wanted to do here is get the name+surname of the users who teach a lesson. Imagine a list tha displays each lesson+who teaches it based on the term that lesson is available.
Looking at http://adodb.sourceforge.net/ I can see an example on the first page on how to use the library:
$rs = $DB->Execute("select * from table where key=123");
while ($array = $rs->FetchRow()) {
print_r($array);
}
So, you should use:
while ($row = $get_teachers->fetchrow()) {
instead of:
for ($j = 0; $j < $get_teachers->fetchrow(); ++$j) {
The idea with FetchRow() is that it returns the next row in the sequence. It does not return the number of the last row, so you shouldn't use it as a condition in a for loop. You should call it every time you need the next row in the sequence, and, when there are no more rows, it will return false.
Also, take a look at the documentation for FetchRow().
for($j=0;$j<$get_teachers->fetchrow();++$j){
... a few lines later ...
$row = $get_teachers->fetchrow();
See how you call fetchrow() twice before actually printing anything? You remove two rows from the result set for every 1 you actually use.
while ($row = $get_teachers->fetchrow()) {
instead and don't call fetchrow() again within the loop.
Because you're fetching twice first in the loop
for($j=0;$j<$get_teachers->fetchrow();++$j){
... some code ...
// And here you fetch again
$row = $get_teachers->fetchrow();
You should use it like this
while ($row = $get_teachers->fetchrow()) {

Categories