Displaying results from SQL query in PHP in a table - php

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)

Related

Show alert message if MySQL php query match one condition [duplicate]

This question already has answers here:
How to pop an alert message box using PHP?
(9 answers)
Closed 1 year ago.
I have an online software that use php, html, js and MySQL as database.
I have two tables:
1- First table contains [name, imei, object_expire, object_expire_dt] - gs_objects
2- Second table contains [object_id, user_id, imei] - gs_user_objects
The code should be done in php where the user_id is got from the session, then the first query should get the imeis that matches the user_id from second table then it should get the expire date 'object_expire_dt' of each imei from the first table
after that it should check if there is an expire date that will expire within 20 days, if true, it should show alert message
Here is incomplete code that I tried to do
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."' ORDER BY `object_id` ASC";
$r2 = mysqli_query($ms, $q2);
while($row=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row['object_expire_dt'] > date('Y-m-d', strtotime($Date_e. ' - 20 days')))
{
alert("You have objects are going to expire soon");
}
}
}
the code didn't work, I need some help in it.
Thanks in advance
Here's how all this works: Your php program runs on your server, and accesses your database on the server. The purpose of your php program is to create programs to run on your users' browsers. Those programs written by php use the HTML, Javascript, and CSS languages.
If you want something to happen in a user's browser (like an alert box) that thing has to appear in a Javascript program written by your php program and sent to the browser. php doesn't have its own alert() function
Here's an easy, but somewhat sloppy, way to do that in your php program.
echo "<script type='text/javascript'>window.onload=function(){alert('$msg'))</script>";
What's going on here?
echo tells php to write its parameter to the html page
<script> whatever </script> is the way to embed Javascript in html
window.onload = function () { whatever } tells the browser to run a Javascript function when your html page finishes loading.
alert(message), in the function, pops up the alert message.
When you're troubleshooting this kind of thing, View Source ... is your friend.
you can use alert in javascript not in php
also you should use prepared statement.
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser'){
$user_id = $_SESSION["manager_id"];
}else{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM gs_user_objects WHERE user_id = ? ORDER BY object_id ASC";
if ($r = $connection->prepare($q)) {
// if user_id contains string and is not integer you must use "s"
$r->bind_param("i",$user_id);
if ($r->execute()) {
$result = $r->get_result();
// check if result match one condition
if ($result->num_rows > 0) {
echo "result found";
while ($row = $result->fetch_assoc()) {
echo $row['some_column_name'];
}
}
}
}
Thanks Nikolaishvili and Jones,
Your answers helped me a lot I needed more edit on the if statements,
I did the code and the result is as I expected and it is online now, here the code is below so others can check it
//notification for objects expiration
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
$expiry_flag = 0;
$inactive_flag=0;
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."'";
$r2 = mysqli_query($ms, $q2);
while($row2=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row2['object_expire_dt'] < date('Y-m-d', strtotime($Date_e. ' + 20 days')))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$expiry_flag = 1;
}
}
if ( $row2['object_expire_dt'] < date("Y-m-d"))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$inactive_flag = 1;
}
}
}
}
if ($expiry_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg1")';
echo '</script>';
}
if ($inactive_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg2")';
echo '</script>';
}
Thanks

Unwanted entry in the database every time I try to do an insert Codeigniter

I'll try my best to explain my current situation so please bear with me.
I really need your help in this because I'm seriously running out of ideas. I was trying to do some queries where the user will not be able to input duplicate entries to the database.
I have 3 databases named Semester, Prereq, and Coreq.
In my view I have this table where I display 5 columns. Three from the Semester database(College Code, Semestral Year, and Subject Code) which I joined(left) with Prereq and Coreq(they both have College Code, Semestral Year, and Subject Code). One column from Prereq(which is prereq) and one column from Coreq(which is coreq). Please note that in both Prereq and Coreq they don't have any unique column.
Now in my php application that uses codeigniter, the user needs to input in either Prereq or Coreq.
Upon testing on some random variable on the Prereq form, the said random variable seem to get stuck every time I enter something to the other form which is Coreq.
So let's say I input something like ABC in the Prereq. That ABC would always be there every time Input something to the Coreq which really shouldn't be happening. Like every time I try to add an entry using the application, for example I choose to add a Coreq named Math101 to some college code with its subject code, in my table view the new row entry with Math101 has a spooky Prereq ABC even though I only entered on the Coreq form.
I have an input page where the user gets to input in two separate forms. They get to add either on the Coreq form or the Prereq form via select tags. These select tags get populated from the same 3 tables by json encode and jquery. The values they can input are College Code, Subject Code, Coreq/Prereq. They can only input in one form at a time. It has two buttons in which if you press Add Coreq, the Prereq form hides via Jquery and vice-versa so I find it very weird that a value I placed before is always there. Kind of spooky.
Here's the codes I was testing out inside my Model:
public function setCoreq(){
$f1 = $_POST['sy'];
$f2 = $_POST['college'];
$f3 = $_POST['subjcode'];
$f4 = $_POST['coreq'];
$query = $this->db->query("SELECT COLLCODE, SY, SUBJCODE, COREQ FROM College_co_req"
. " WHERE COLLCODE ='$f2' AND SY = '$f1' AND SUBJCODE = '$f3' AND COREQ = '$f4'");
$num = $query->num_rows();
if($num==0){
$this->db->query("INSERT IGNORE INTO College_co_req VALUES('$f1', '$f2', '$f3', '$f4')");
return true;
}else{
return false;
}
}
public function setPrereq(){
$f1 = $_POST['sy'];
$f2 = $_POST['college'];
$f3 = $_POST['subjcode'];
$f4 = $_POST['prereq'];
$query = $this->db->query("SELECT COLLCODE, SY, SUBJCODE, PREREQ FROM College_pre_req"
. " WHERE COLLCODE ='$f2' AND SY = '$f1' AND SUBJCODE = '$f3' AND PREREQ = '$f4'");
$num = $query->num_rows();
if($num==0){
$this->db->query("INSERT IGNORE INTO College_pre_req VALUES('$f1', '$f2', '$f3', '$f4')");
return true;
}else{
return false;
}
}
The boolean will then get passed to my Controller and my controller redirects the user to either an error_input page(if it returns false) or the view page that shows the table with 5 columns(when true).
Here's my controller:
public function insertCoreq() {
$check = $this->triune_colleges_model->setCoreq();
if($check == false){
$this->load->view('input_error');
}else{
$data['results'] = $this->Model->subject_all();
$this->load->view('table_view', $data);
}
}
public function insertPrereq() {
$check = $this->triune_colleges_model->setPrereq();
if($check == false){
$this->load->view('input_error');
}else{
$data['results'] = $this->Model->subject_all();
$this->load->view('table_view', $data);
}
}
The input_error page technically has the same things from my input page. The only difference is that it has a div tag with a class of error which displays a message that disappears via a jquery.
I tried going into the console and disabling cache as well as going through the trouble of deleting my browsing history, cookies, autofill, and passwords, for the whole day. But the spooky Prereq entry still persists.
The only time the spooks happened was when I placed the
$query = $this->db->query("SELECT COLLCODE, SY, SUBJCODE, COREQ FROM College_co_req"
. " WHERE COLLCODE ='$f2' AND SY = '$f1' AND SUBJCODE = '$f3' AND COREQ = '$f4'");
$num = $query->num_rows();
if($num==0){
$this->db->query("INSERT IGNORE INTO College_co_req VALUES('$f1', '$f2', '$f3', '$f4')");
return true;
}else{
return false;
}
code from the insertCoreq to the insertPrereq since it was working when I tried it out a few days ago.
Any suggestion/solution is appreciated. Please help x'D
Here's how I display my table on my view if anyone's willing to check it:
<?php foreach ($results as $results_item): ?>
<tr>
<td>
<?php echo $results_item['CollCode']; ?>
</td>
<td>
<?php echo $results_item['SY']; ?>
</td>
<td>
<?php echo $results_item['SubjCode']; ?>
</td>
<td>
<?php echo $results_item['Coreq']; ?>
</td>
<td>
<?php echo $results_item['Prereq']; ?>
</td>
</tr>
<?php endforeach; ?>
Here's my query from my Model:
$this->db->select('college_semester.SubjCode, college_semester.CollCode, college_semester.SY, college_pre_req.Prereq, college_co_req.Coreq');
$this->db->from('college_semester');
$this->db->join('college_co_req', 'college_semester.CollCode = college_co_req.CourseCode AND college_semester.SubjCode = college_co_req.SubjCode AND college_semester.SY = college_co_req.SY', 'left');
$this->db->join('college_pre_req', 'college_semester.CourseCode = college_pre_req.CourseCode AND college_semester.SubjCode = college_pre_req.SubjCode AND college_semester.SY = college_pre_req.SY', 'left');
$query = $this->db->get();
return $query->result_array();
and here's from my Controller:
$data['results'] = $this->Model->subject_all();
$this->load->view('table_view', $data);
Check for the problem in two areas at time of data insert and data fetch.
Have you checked data in both the table in database ? check for the data which you have inserted is exist in both the table or in desired table using database console.
check how 'table_view' is populating data. check the query it use to fetch data.
Regards,

Switch Statement based on if variables in two tables match

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.

PHP / MySQL Simple IF / ELSE not so simple

I think my mind must be going through a Boxing Day mess.
I am building a basic comment section for every game a sports team plays.
So, when no comments are entered (in the MySQL DB), I simply want to display "Be the first to enter a comment"; otherwise, display the comment results table in html format.
I can easily display the comment result table.
For some reason, I can't get the IF no comments to work properly. Feel so amateurish right now . . . :-)
I have declared row count:
$row_count = 0;
I am adding to the count inside the while statement
while($row = mysql_fetch_array($result))
{
// adding to count
$row_count++;
My count is working as I can display the row number to the screen.
Here is IF / ELSE my code:
if ($row_count === 0) {
echo "<p>Be the first to enter a game comment and earn points toward your next fan badge.</p>";
} else {
// no need to show code as this already works!
you can use
mysql_num_rows($queryReference)
Hope this helps.
Thanks.
Please do one thing print this value using below function and tell me what is output
var_dump($row_count);
or you can use == instead of ===
$query = mysql_query("SELECT * FROM comments");
$c = mysql_num_rows($query);
if($c==0) {
echo "<p>Be the first to enter a game comment and earn points toward your next fan badge.</p>";
}
else {
while($row = mysql_fetch_array($query))
{
$vars = $row[index];
}
}
$row_count = 0;
I am adding to the count inside the while statement
while($row = mysql_fetch_array($result))
{
// adding to count
$row_count++;
}
My count is working as I can display the row number to the screen.
Here is IF / ELSE code:
if ($row_count == 0) {
echo "<p>Be the first to enter a game comment and earn points toward your next fan badge.</p>";
} else {
// no need to show code as this already works!
}

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.

Categories