Trying to get a page to populate data from a database - php

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.

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.

Remove Array From Json in PHP

hi i have a backend with php in cpanel and i have a problem with one of jsons . this is part of my php code :
...
}elseif ($work == "dollardate") {
$query3 = "SELECT * FROM tabl_dollar_date";
$result3 = $connect->prepare($query3);
$result3->execute();
$out3 = array();
while ($row3 = $result3->fetch(PDO::FETCH_ASSOC)) {
$record3 = array();
$record3["dollar"] = $row3["dollar"];
$record3["date"] = $row3["date"];
array_push($out3, $record3);
}
echo json_encode($out3);
}
?>
this code show this in json :
[
{
"dollar":"15000",
"date":"1397-12-12"
}
]
how can remove array from json and show the json like this :
{
"dollar":"15000",
"date":"1397-12-12"
}
Easiest way (according his code):
change line
echo json_encode($out3);
to
echo json_encode($out3[0]);
One solution is that if you just want the latest value (in case there are multiple records in the table), then change the SELECT to order by date descending also set LIMIT to 1 to only get the 1 record anyway, and remove the loop to fetch the data and just fetch the 1 record...
$query3 = "SELECT `date`, `dollar`
FROM `tabl_dollar_date`
ORDER BY `date` desc
LIMIT 1";
$result3 = $connect->prepare($query3);
$result3->execute();
$row3 = $result3->fetch(PDO::FETCH_ASSOC);
echo json_encode($row3);
As you know which fields you want from the SELECT, it's good to just fetch those fields rather than always using *. This also means that as the result set only contains the fields your after, you can directly json_encode() the result set rather than extracting the fields from one array to another.

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)

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 JOIN with matching column names

Noticed a rather large problem. When I join two tables togeter the fact that there is a column called ID in both of them causes the wrong tables ID to be used in a PHP equasion later on.
The simple solution would be to change the column name, but there are other standards thoughout the database too including columns called name in every table and title in many of them.
Is there a way around this or should I rename the entire database to ensure that there are no duplicate columns.
THE CODE FOR REFERENCE
$criteria = "SELECT *
FROM voting_intention,electors
WHERE voting_intention.elector = electors.ID
AND electors.postal_vote = 1
AND voting_intention.date = (select MAX(date)
from voting_intention vote2
where voting_intention.elector = vote2.elector)
AND electors.telephone > 0"
function get_elector_phone($criteria){
$the_elector = mysql_query("SELECT * $criteria"); while($row = mysql_fetch_array($the_elector)) {
return $row['ID']; }
While "Gunnx" solution is perfectly acceptable, I'd like to present an alternative since you appear to be using only the ID column of the result.
SELECT
electors.ID
FROM
voting_intention,electors
....
I wrote this function to assist in doing this. Basically it prepends the table name to the fields name of an associated array.
while($row = mysql_fetch_array($the_elector))
{
return $row['ID'];
}
would become
while($row = mysql_fetch_table_assoc($the_elector))
{
return $row['voting_intention.ID'];
}
function:
function mysql_fetch_table_assoc($resource)
{
// function to get all data from a query, without over-writing the same field
// by using the table name and the field name as the index
// get data first
$data=mysql_fetch_row($resource);
if(!$data) return $data; // end of data
// get field info
$fields=array();
$index=0;
$num_fields=mysql_num_fields($resource);
while($index<$num_fields)
{
$meta=mysql_fetch_field($resource, $index);
if(!$meta)
{
// if no field info then just use index number by default
$fields[$index]=$index;
}
else
{
$fields[$index]='';
// deal with field aliases - ie no table name ( SELECT T_1.a AS temp, 3 AS bob )
if(!empty($meta->table)) $fields[$index]=$meta->table.'.';
// deal with raw data - ie no field name ( SELECT 1, MAX(index) )
if(!empty($meta->name)) $fields[$index].=$meta->name; else $fields[$index].=$index;
}
$index++;
}
$assoc_data=array_combine($fields, $data);
return $assoc_data;
}
?>
mysql_fetch_row will get the data as a numerical array

Categories