PHP Function produces empty Results no errors - php

A little help if possible. I have a Page that pulls from two data tables (MySQL) and one function is providing empty results.
function ShowClient() {
global $agent;
$sql = 'SELECT * FROM nuke_bulletins WHERE user=\'' . $agent . '\' AND isActive="Y" ORDER BY id';
$client = mysql_query($sql) or die('ERROR: OOPS Something went wrong' . mysql_error());
echo '<center><p><b>Current Campaigns</b></p>';
// Pull the loop and display the data
while($row = mysql_fetch_array($client)) {
$agent = stripslashes($row['user']);
$campaign = stripslashes($row['id']);
$title = stripslashes($row['title']);
echo '<p><b>' . $title . '</b></p>';
}
echo '<p>Click the Campaign Title to get the Bulletin Code</p><p> </p>';
echo '<p align="center"><b>Return to All Client\'s</p>';
}
The $agent variable is pulled from a main function that creates a url based on the user ($agent).
What am I doing wrong here?

$agent is a global variable. Using global variables is generally considered bad practice, as this could be getting set or unset somewhere before this function is called.
Have you checked the PHP Error Log to see if you are getting any errors?
If no errors in log I would look to see if $agent conatins a value either by echoing to screen (if dev environment) or dumping the value in the error log file to see if it actually contains anything. http://www.php.net/manual/en/function.error-log.php
Then I would look at the SQL itself; do the Column headings in your table nuke_bulletins match the $row array keys exactly for instance are they the same case?
$row['title']
or
$row['Title']

Here we go...
Don't use the mysql extension. It is unmaintained and officially deprecated
Don't use globals. Relying on external state makes for smelly code
You're overwriting said global variable ($agent) in a loop. Terrible idea.
or die must die ~ http://www.phpfreaks.com/blog/or-die-must-die
I wouldn't recommend using echo within a function. Makes for spaghetti code
Your HTML is a bit of a mess
Here's my suggestion using the mysqli extension
function getCampaigns(mysqli $con, $agent) {
if (!$stmt = $con->prepare("SELECT id, title FROM nuke_bulletins WHERE user = ? AND isActive = 'Y' ORDER BY id")) {
throw new Exception($con->error, $con->errno);
}
$stmt->bind_param('s', $agent); // if the user column is a integer, use 'i' instead
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
$stmt->bind_result($id, $title);
$campaigns = []; // or array() if you're on PHP < 5.4
while ($stmt->fetch()) {
$campaigns[$id] = $title;
}
return $campaigns;
}
Now you can call this function like this...
<?php
// assuming you have a mysqli instance in a $con variable, eg $con = new mysqli(...)
// and an $agent variable
$campaigns = getCampaigns($con, $agent);
?>
<p><strong>Current Campaigns</strong></p>
<?php foreach ($campaigns as $id => $title) : ?>
<p>
<a href="bullies2.php?op=ShowCampaign&id=<?= $id ?>">
<strong><?= htmlspecialchars($title) ?></strong>
</a>
</p>
<?php endforeach ?>
<p>Click the Campaign Title to get the Bulletin Code</p>
<p> </p>
<p align="center"><strong>Return to All Client's</strong></p>
And, as always, your development environment should have the following properties set in your php.ini file
display_errors = On
error_reporting = E_ALL

Related

PHP function not browsable

I'm trying to build an API with a JSON output, the second function is producing the desired output however I can't call it from the web. Whereas the first function returns as expected a large mass of text. Am I using something that is not compatible? I'm using version PHP 5.5.9 on an Ubuntu 14.04 server.
I can view the result of this function in both the terminal and the browser;
<?php
class ArticlesAPI {
function top() {
$db = new mysqli("mysql-host.rds.amazonaws.com", "user", "password", "db_name");
$results = $db->query("SELECT article_id, title, summary FROM top_articles");
while ($row = $results->fetch_assoc()) {
echo $row['article_id'];
echo $row['title'];
echo $row['summary'];
}
$results->close();
}
}
$api = new ArticlesAPI;
$api->top();
?>
This function only returns a result in the terminal;
<?php
class ArticleAPI {
function top() {
$db = new mysqli("mysql-host.rds.amazonaws.com", "user", "password", "db_name");
$results = $db->query("SELECT article_id, title, summary FROM top_articles");
$articles = array();
while($article = $results->fetch_assoc()){
$article_id = $article['article_id'];
$articles[$article_id][] = $article['title'];
$articles[$article_id][] = $article['summary'];
}
$results->close();
$db->close();
$json = json_encode($articles);
echo $json;
}
}
$api = new ArticleAPI;
$api->top();
?>
There are 2 separate configuration files for CLI and for WEB check them and check server configuration(if http server parse php files etc.) you can do simple <?php echo 'hello world'; and see if output is correct. If you open it via browser and you see anything more than hello world then PHP parser is not enabled.
Also when you output JSON you should set proper header for browser application/json
Check your output buffering settings. Maybe you use ob_* functions and don't flush output to browswer
Try putting exit after echo and check script after.
Set error_reporting(E_ALL); and ini_set('display_errors', 1); in first line of your app to check if there are errors.

Use ISSET from some of the examples here on stackoverflow Error on the Code

I Dont think I wrote the code correctly. Can someone look at this? I am new to php!
<?php
// Create Connection
$connect = mysqli_connect('localhost','root','test123','joomla');
// Check Connection
if(mysqli_connect_errno($connect)) {
echo 'Failed to connect to DataBase| '. mysqli_connect_error();
}
?>
I added if(issets($_GET['rp_id'])) to the if rp_id does not exist in the url parameter - it just closes the database
<?php
if(issets($_GET['rp_id]')) {
$rp_id = htmlspecialchars($_GET["rp_id"]);
// open record with evdet_id =$rp_id
$result = mysqli_query($connect,"SELECT * FROM n0dap_jevents_vevdetail WHERE evdet_id =".$rp_id);
while($row = mysqli_fetch_array($result)):
$value = $row['google_map'];
echo $value;
endwhile;
}
$connect->close();
//if the rp_id does exist the go ahead and run the top otherwise close it.
} else {
$connect->close();
}
?>
if(issets($_GET['rp_id]))
Looks like you made a typo on isset().
Call to undefined function issets()
This means you're trying to call issets() as a function, which it is not.
The function that you are looking for is isset(). If you replace issets() with isset(), you will not longer get that error message.

PHP Session Not Saving Upon Refresh

So, I have a PHP class that has a method which updates a session variable called $_SESSION['location']. But the problem is, each time the method is called, it doesn't find the saved session variable, and tells me it isn't set. It's supposed to store a location ID, and the method pulls the next location from a MySQL database based on the session variable, then storing the new ID. But the place in the SQL code, that's supposed to include the variable, is empty.
I do have session_start() at the beginning of the page. I've tried manually setting the variable, and it doesn't do anything either. Also tried to reach that variable from another PHP page, and no luck either. Please help.
Small sample of my code:
class location {
#session_start();
function compass($dir) {
$select = $_SESSION['location'];
if($dir == "north") {
$currentlat = mysql_result(mysql_query("SELECT `lat` FROM `locationdb` WHERE id=".$select), 0, "lat");
$currentlon = mysql_result(mysql_query("SELECT `lon` FROM `locationdb` WHERE id=".$select), 0, "lon");
$sql = "[THE SQL CODE THAT GETS THE NEXT LOCATION]";
$id = mysql_result(mysql_query($sql), 0, "id");
$_SESSION['location'] = $id;
$return['loc'] = $this->display_location($id);
$return['lat'] = $this->display_lat($id);
$return['long'] = $this->display_long($id);
$return['id'] = $id;
}
return $return;
}
}
I have tested your code
**Dont use session_start() in this file.
For simple testing first add this inside your compass() function.
$_SESSION['location'] .= 'World';
Then create a php script with these codes.
<?php
session_start();
$_SESSION['location'] = 'Hello';
include_once('*your name of class file*');
$obj = new location();
$obj -> compass('north');
echo $_SESSION['location'];
?>
Run this script
If the output is "HelloWorld" then your $_SESSION['location'] is working.
Check your phpinfo(), to see if the session save path is defined. If not, define a directory to store the sessions. In your code:
session_save_path('/DIRECTORY IN YOUR SERVER');
Then try again.
This is closer to what your method should look like. There are some settings that will help reduce errors being thrown when running the function. With this function, and other suggestions, you should be able to remove the error your are getting.
class location
{
public function compass($dir = '')
{
// Set the $select by $_SESSION or by your function
$select = (isset($_SESSION['location']))? $_SESSION['location']: $this->myFunctionToSetDefault();
// I set $dir to empty so not to throw error
if($dir == "north") {
$currentlat = mysql_result(mysql_query("SELECT `lat` FROM `locationdb` WHERE id=".$select), 0, "lat");
$currentlon = mysql_result(mysql_query("SELECT `lon` FROM `locationdb` WHERE id=".$select), 0, "lon");
$sql = "[THE SQL CODE THAT GETS THE NEXT LOCATION]";
$id = mysql_result(mysql_query($sql), 0, "id");
$_SESSION['location'] = $id;
$return['loc'] = $this->display_location($id);
$return['lat'] = $this->display_lat($id);
$return['long'] = $this->display_long($id);
$return['id'] = $id;
}
// This will return empty otherwise may throw error if $return is not set
return (isset($return))? $return:'';
}
}

Eve API xml to php

I have managed to create a mysql database with itemIDs and Item types. so far all I have managed to do is generate a button that opens a url to eve api that grabs the prices from eve central. I can't currently post images.
The php code then generates an api url to show the prices which eventually my plan is to grab the Max Buy Prices and Min sell prices and perform on of the following on them:
if the corp needs the item it will be (maxbuyprice + Minsellprice)/2
if the corp doesn't need the item the calculation will be ((maxbuyprice + Minsellprice)/2) * 0.9
My problem is getting php to parse the xml instead of showing the xml document - I did this for debugging or seeing the data that is available.
for an example the url that I generated with Veldspar is:
generated url using Veldspar is the item name
index.php file:
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/db.inc.php';
$pagetitle = 'HoMs Asset Management System - Create Contract';
$pagedescription = 'HoMs Asset Management System for managing Corporation Contracts and Pricing';
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/access.inc.php';
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/ObjectClasses.inc.php';
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/helpers.inc.php';
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/EveCentral.inc.php';
if (isset($_POST['action']) and $_POST['action']=='View Eve Central Prices')
{
$itemname = html($_POST['ItemName']);
calculateAskingPrice($itemname);
}
include 'createcontract.html.php';
?>
db.inc.php file:
<?php
//local dbstrings
//production dbstrings
$dbhost='localhost';
$dbusername='homedata1';
$dbpassword='EzPKfmxcTKAeSnDs';
$dbname='homdata';
Function connect2db()
{
Global $dbhost;
Global $pagetitle;
Global $pagedescription;
Global $mysqlport;
Global $dbname;
Global $dbusername;
Global $dbpassword;
Global $pdo;
Global $error;
Global $curNewsMessage;
Global $logged;
Global $ItemList;
try
{
$pdo = new PDO('mysql:host=' .$dbhost .';dbname=' .$dbname .';port=' .$mysqlport, $dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
return TRUE;
}
catch (PDOException $dbconerr)
{
$pagetitle = 'Hom Asset Management - Database Connection Error';
$pagedescription = 'There was a problem connecting to the database';
$error = 'Unable to connect to the database server:' ."\n\n"
.'The database in which this pages content relies on is unavailable or, for other reasons is not contactable' ."\n"
.'I am liasing with my website host to get this resolved as quickly as possible. Please check later.' ."\n"
.'sorry for any inconvenience' ."\n\n" .'This information may help to diagnose the problem: <br>' .$dbconerr;
$logged = 'Sorry. The interactive areas are unavailable because the database is unavailable';
$curNewsMessage = 'News message unavailable. ' ."\n" .' Database connection error';
return FALSE;
}
return TRUE;
}
EveCentral.inc.php file:
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/helpers.inc.php';
function calculateAskingPrice($Item)
{
// Connect to the database and search for the item posted
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/db.inc.php';
Global $pdo;
Global $itemname;
if (connect2db())
{
$sql = "SELECT * FROM `itemtypes` WHERE ItemName=:itemname";
$s = $pdo->Prepare($sql);
$s->bindValue(':itemname',$Item);
$s->execute();
$row = $s->fetch();
if ($row > 0)
{
$itemid = html($row['ID']);
$evecurl = 'http://api.eve-central.com/api/marketstat?typeid=' .$itemid .'&usesystem=30000142';
header('Location: ' .$evecurl);
}
else
htmlout('Item not found: ' . $itemname);
}
else
{
echo 'problem connecting to database';
}
}
?>
here i got some version how can help us both:
$xml = simplexml_load_file('http://api.eve-central.com/api/marketstat?usesystem=30000142&hours=24&typeid=3683&minQ=10000');
echo $xml->marketstat->type->sell->min; // 257.99
Im a little comfused, are you wanting help parsing the EVE API xml or the mineral pull XML from eve central?
If it is the price XML, here is what i use, this is on my main page...
// Get Mineral Prices
GetCurrentMineralPrice();
$TritPrice = $ItemPrice[1];
$PyerPrice = $ItemPrice[2];
$MexPrice = $ItemPrice[3];
$IsoPrice = $ItemPrice[4];
$NocxPrice = $ItemPrice[5];
$ZydPrice = $ItemPrice[6];
$MegaPrice = $ItemPrice[7];
$MorPrice = $ItemPrice[8];
and this is the function it calls.
function GetCurrentMineralPrice() {
global $ItemPrice;
$xml = simplexml_load_file("http://api.eve-central.com/api/marketstat?typeid=34&typeid=35&typeid=36&typeid=37&typeid=38&typeid=39&typeid=40&typeid=11399&usesystem=30000142");
$i = 1;
foreach ($xml->marketstat->type as $child) {
$ItemPrice[$i] = $child->buy->max;
$i++;
}
return $ItemPrice;
}
For the sell max price change this line...$ItemPrice[$i] = $child->sell->min;
if you are wanting to parse the EVE API, thats an entirely different story, that I havent mastered yet since each API XML is different...

$_post not posting in php and mysql database

I have the the following code however the data only goes into the applicant table and not the applicant_edit table, and apparently I am having this error around the program, I may think it has something to do with the $_post but im not sure, also I have the same exact application running on another computer and it works fine, here is what i did, on this new machine, whiche seems to not be working well, I installed apache, then copied over my entire server folder with all the setting from my other machine, most things seem to be working however when it comes to $_post, thats where errors occur. Please Id love some help and suggestions.
<?php
include("config.php"); // put the *FULL* path to the file.
$url = 'index.php';
header('Location: ' . $url);
//header('Location: ' . $url);
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sq1="INSERT INTO applicant (app_trn,app_file_id, app_fname, app_lname,app_mid_name, app_strt_add_1, app_strt_add_2,app_city, app_parish, app_postal,
app_hme_cntct, app_cell1_cntct, app_cell2_cntct, app_email, app_gov_agncy, app_gov_agncy_strt,app_gov_agncy_city, app_gov_agncy_parish, app_post,
app_grade,app_appointment_date,app_salary,app_gov_last_agncy1,app_gov_last_agncy1_street,app_gov_last_agncy1_city,app_gov_last_agncy1_parish,
app_gov_last_agncy1_contact, app_gov_last_agncy2, app_gov_last_agncy2_street,app_gov_last_agncy2_city,app_gov_last_agncy2_parish,app_gov_last_agncy2_contact,
app_gov_last_agncy3,app_gov_last_agncy3_street,app_gov_last_agncy3_city,app_gov_last_agncy3_parish,app_gov_last_agncy3_contact)
VALUES
('$values[app_trn]','$values[app_file_id]', '$values[app_fname]','$values[app_lname]', '$values[app_mid_name]','$values[app_strt_add_1]', '$values[app_strt_add_2]',
'$values[app_city]', '$values[app_parish]', '$values[app_postal]', '$values[app_hme_cntct]', '$values[app_cell1_cntct]', '$values[app_cell2_cntct]',
'$values[app_email]', '$values[app_gov_agncy]', '$values[app_gov_agncy_strt]', '$values[app_gov_agncy_city]', '$values[app_gov_agncy_parish]','$values[app_post]',
'$values[app_grade]','$values[app_appointment_date]','$values[app_salary]','$values[app_gov_last_agncy1]','$values[app_gov_last_agncy1_street]',
'$values[app_gov_last_agncy1_city]','$values[app_gov_last_agncy1_parish]','$values[app_gov_last_agncy1_contact]', '$values[app_gov_last_agncy2]',
'$values[app_gov_last_agncy2_street]','$values[app_gov_last_agncy2_city]','$values[app_gov_last_agncy2_parish]','$values[app_gov_last_agncy2_contact]',
'$values[app_gov_last_agncy3]','$values[app_gov_last_agncy3_street]','$values[app_gov_last_agncy3_city]','$values[app_gov_last_agncy3_parish]',
'$values[app_gov_last_agncy3_contact]')";
$result = mysql_query($sq1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
mysql_query("INSERT INTO applicant_edit (applicant_edit_id,edit_app_trn)
VALUES ('','$values[app_trn]')");
?>
You're redirecting all traffic to index.php before anything happens
$url = 'index.php';
header('Location: ' . $url);
Remove that and see what happens
1- Remove header redirect code as mentioned by Paul
2- Try to print out one value
echo $values[app_trn];
echo "'$values[app_trn]'"; //test same case (double quota and single quota)
if it works, then, it will be sql error, try to print
echo mysql_error();
3-
I also suggest to use:
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
after this add:
foreach ($values as $kc => $vc){
$$kc = $vc;
}
now all values can be accessed by using key names:
VALUES
('$app_trn','$app_file_id', '$valuesapp_fname', ...

Categories