echo not displaying value on page - php

I have used "echo $query" to see whether it is getting value or not but it is not showing anything on the page. What is the other way to see what value it is getting?
I use Aptana Studio 2.0 PDT but I am not able to set the breakpoints. Quite new in it.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$ulName = $_GET['ControlName'];
$query = $_GET['SqlQuery'];
echo $query;
mysql_connect('localhost:3306','pffsddsf','dfsdfsd');
mysql_select_db('publicdb');
$result=mysql_query("select * from electioncategorymaster");
?>
<ul id="<?php echo $ulName; ?>" name="<?php echo $ulName; ?>">
<?php while($row=mysql_fetch_array($result))
{ ?>
<li><?php echo $row[1]; ?></li>
<?php } ?>
</ul>

You may not be getting the parameters you expect, so start your script with
var_dump($_GET);
to see what your page is actually getting.
While I appreciate you are just learning, accepting parameters which are passed verbatim to the database server and to the client browser is a security no-no.
Take the $ulName variable - I could inject HTML of my choosing there, so why not constrain it to alphanumerics?
if (preg_match('/[^a-z0-9_]/i', $ulName)
die("Invalid ControlName specified");
As for accepting SQL via a parameter, I really wouldn't do that unless you trust the user of your application completely....
?SqlQuery=DROP+DATABASE+publicdb
Scary right? Now how about if you combined both these flaws? I could craft a link which displayed your page, but embedded a form with hidden fields containing that query, along which a big button which said "click me for funny cat videos". Now I just need to send the link out there and wait for someone else to do my evil bidding :)

Try var_dump($query); (will also report/show empty strings)
If your page is completely blank a look into your apache (or webserver of your choice) errorlogs could also be helpful.

try this:
var_dump($query);
exit;
and see what's happens.

This may sound useless, but you should also copy in an 'example' URL that you are using.
PHP is case-sensitive (especially when it comes to array keys) so for one, I would check that the URL that you are calling is using the correct case when it comes to the GET parameters.

When this simple method fails to show any value the question naturally arises: "Is echo working or is there no value to display?"
I did something similar a while ago, but rather than use echo, I used
printf("[%s]", $query);
So I could see the empty [] when there was no value returned by $_GET

first: enable error logging and also log to a logfile.
error_reporting(E_ALL);
ini_set('display_errors','On');
you can try if your error logging is working by doing the following:
error_log("This Error should be displayed!", 0);
see more about error handling and logging on the php.net site: http://www.php.net/manual/en/book.errorfunc.php

Related

$_GET is not working

Creating a rating system and the info is not being transmitted through my $_GET variable. The code is below
if (isset($_GET['item'], $_GET['rating'])){
echo 'Works!';
}
The variable is being entered in this code below
<?php echo number_format(
$article['rating'],1); ?>
<div class = "rate">
Rate:
<?php
for ($x =1; $x<= $maximum_rating; $x++){
?>
<a href="prestige.php?item=<?php echo $article['id']; ?>&rating=<?php echo $x;?>">
<?php echo $x; ?></a>
<?php
}
?>
I am fairly new to programming so any ideas or tips would be greatly appreciated.
There are a couple of things you should do.
1.
Instead of
prestige.php?item=<?php echo $article['id']; ?>&rating=<?php echo $x;?>
Use
prestige.php?<?= http_build_query(array('item' => $article['id'], 'rating' => $x), '&') ?>
This will escape the parameters. Vars $article['id'] and $x could contain characters that break the HTML or URL.
2.
Look at the Net tab in your Firebug/Chrome dev toolbar. Are there any redirects? What headers are sent?
Also look at the address bar to see if prestige.php really is loaded with the GET parameters.
3.
Use a debug tool like XDebug to step through your code. You might have some code that resets the $_GET vars. Personally I use the IDE PHPed, but it's kinda expensive.
The code you posted works. So the snag must be in the code you did not post:
maybe the prestige.php page has a PHP error that prevents it from displaying anything; start with an empty file containing just <?php echo 'OK so far'; ?>.
maybe the page contains code (security checks, frameworks...) that kills $_GET. (reduce the page to a minimum working case, without include/requires)
maybe the page does work, but the output gets snarked by an untimely ob_end_clean() that was meant to "clean the page" before the real output started; (reduce the page to a minimum working case)
maybe the page works, the string 'Works' is there, but you can't see it due to HTML markup, CSS, or other rendering problems (check the page source)
the URL might be broken because the item code contains invalid URL characters (check what appears in the browser address bar)
there might be an URL rewrite scheme that interferes (check .htaccess and the server logs)
I just remembered something like this happening with international characters in the URL. Try with an ASCII-clean item code to see what happens.
Just to be sure: verify there is no auto_prepend'ed file which might interfere.
Then, it might also be more than one of the above acting together. Often when debugging one unintentionally breaks some code, and even after fixing the first bug, the code doesn't start working again - this doesn't mean the fix was invalid.
I'm sorry -- I'm at the end of my options. I really look forward to knowing what the reason was. (Usually the more explanations I amass, the more the real answer tends to be "none of the above". When it happens to me, sometimes I wonder whether to start to believe in gremlins :-( ).

PHP variables and XML elements

I'm trying to use PHP variables to load certain elements from a XML file, so if index.php?id=1 is loaded it would pull the information from $projects->project[1]. No errors come up in the following code, but nothing gets displayed. Any help is appreciated :)
<?php
$projects = simplexml_load_file('portfolio.xml');
$id = $_GET["id"];
echo $projects->project[$id]->title;
?>
It may be one of two things (or both):
echo doesn't show anything if there is nothing to show.
there has been an error, but your server is not reporting it, try checking logs if there are any. Also check if error reporting is enabled.
That said, try using print_r or var_dump to get the data.
print_r($_GET); die;
to check if u are getting the data in get or not .
error_reporting(~0); // show me everything i do wrong
$projects = simplexml_load_file('portfolio.xml');
var_dump($projects); // make sure $projects actually has something
var_dump($_GET['id']); // are you getting the request data?
$id = (int) $_GET["id"]; // cast to int for good measure
// i'm assuming it's numeric, don't if its not
echo $projects->project[$id]->title; // still not showing anything?
var_dump($projects->project[$id]->title); // dump it for good measure

Pass multiple variables via URL and reading all of them on next page

I have a link that points to a webpage e.g. "land.php".
The link looks like this:
link
this takes me to the page land.php where I can read the first parametere with $id (and it is equal to 1, correctly), but I cannot read the second one. I either tried with $cd or $_GET['cd']. None of them works.
if I tried isset($cd) it says false. Same thing for isset($_GET['cd']).
How can I pass the second parameter too (and read it!)?
EDIT:
some code (so people are happy. I think it's pointless in this case..).
land.php
<?php
if($_GET['cd']==a)
echo "<h2>HI</h2>";
else
echo "<h2>BY</h2>";
?>
if I use $cd instead of $_GET['cd'] it doesn't work anyway..
EDIT2 I don't get any syntax error, it just doesn't behave how expected.
The value is stored in $_GET['cd'].
Try printing out the $_GET array, with print_r($_GET);
print_r($_GET) should output
Array
(
[id] => 1
[cd] => a
)
This should ofcourse be in the land.php page, as the get variables are only available in the requested page.
Your server might be set up to accept semicolon instead of ampersands. Try replacing & with ;
$_GET['cd'] is the correct syntax. Are you actually on the land.php page, ie does your browser's address bar read something like
example.com/land.php?id=1&cd=a
Also, it looks like you have register_globals enabled if you can read $id. This is a very bad idea.
Update
Your code snippet contains syntax errors. I recommend the following, including enabling decent error reporting for development
ini_set('display_errors', 'On');
error_reporting(E_ALL);
if(isset($_GET['cd']) && $_GET['cd'] == 'a') {
echo "<h2>HI</h2>";
} else {
echo "<h2>BY</h2>";
}

PHP Function 'return' not returning

This is a bit of an oddity for me. PHP is my forte, and I can normally figure out any issue I encounter.
I have a custom framework that I have been using for years. I have taken it upon myself to rewrite it, and I'm doing everything essentially the same that I was before. The problem lies in the following construct:
function ModPages_GetPage() {
$page = ModPages_GetPageByName($_GET['page_name']);
if($page != false) {
include(TPL_DIR.'pages/pages.view.php');
} else {
ErrorMessage('Invalid Page', 'The selected page could not be found.');
}
}
function ModPages_GetPageByName($page_name = null) {
$db = new Database;
$query = '
SELECT *
FROM pages
WHERE page_name = "'.CleanStr($page_name).'"
AND page_enabled = "yes"
LIMIT 1
';
$page = $db->GetRow($query);
return $page;
}
This code is being called with 'home' for the value of $_GET['page_name']. The call to ModPages_GetPageByName() is working fine, but the value of $page in ModPages_GetPage() isn't getting set. Matter of fact, any debugging statements thrown in after that call are failing to display anything.
I have display_errors set to on, and error_reporting set to E_ALL. I get a couple notices from my Database class, but that's it.
Running the script at a shell fails to produce any errors. When using strace, I do see the process spits out an 'exit_group(255)'.
This one has me quite baffled. I could sure use some direction on this.
I would think it's your query, shouldn't you just return the page name instead of star? as star (*) would return an array which is probably being passed back as the value? just my guess.
$query = '
SELECT *
FROM pages
WHERE page_name = "'.CleanStr($page_name).'"
AND page_enabled = "yes"
LIMIT 1
';
if you do a print_r on the $page return I would think it should be an array
$page = $db->GetRow($query);
echo "Page:<pre>".print_r($page,true)."</pre><br />\n";
Then maybe return something like this
return $page['page_name_field'];
ok before we get to a solution can we first make sure that before setting the $page variable, first just echo $_GET['page_name'] to see if there is a value being received.
PK
Does your script stop right after your database call, or just doesn't display any output?
If the first is true, then it looks like a fatal error. With E_ALL, it should be displayed, are you sure both display_errors and error_reporting are as you say at that point, and that the GetRow function doesn't alter them in any way? If so, maybe there's something in the Apache error log (PHP errors are sometimes logged there).
If the latter is true I'm thinking about an exception being thrown in a method that is being called, and caught in a higher level function. To check this you can put the database call (ie: the point where things go wrong) inside a try/catch block and see if you reach the catch block.
I would try following:
replace $_GET with $_REQUEST (maybe your form is using POST?)
do a print_r to check contents of your variables.
use mysql_error to view any errors, or print your mysql query in your browser, copy/paste it in phpmyadmin, is it returning anything? error.. data?
something similar happend to me once, my framework was encoded in ANSI and my calling php file was UTF8+BOM... I changed everything to UTF8+BOM and it worked.
try also different browser, I know it might not be a browser problem, but it might be that your script is cached somewhere.
are you using some caching? like eaccelerator?
Are those functions in a class? If so, you will need $page = $this->ModPages_GetPageByName().
Also I would echo out the argument and the sql statment in ModPages_GetPageByName(). This way you can verify that it isn't a SQL error.
I can't say for sure why your code isn't working, but I can make some suggestions that might help in locating the error.
The first thing I notice is you don't check that $db actually contains a valid database. I don't know the details of your Database object but I'm assuming there's some mechanism in there for checking if it's actually connected to the database. You should use that to determine if the database is connected before running queries on it.
$db = new Database ();
if ($db -> isConnected ())
{
$query = 'SELECT * (etc etc etc)';
// ...
}
else
{
// Put some kind of DB connection error notification or throw an exception here
}
Just on a stylistic note, you don't need to store the results of your DB lookup before returning it, unless you're planning on doing some processing on the result before returning it. You can just return the lookup directly. Of course that's just a stylistic choice, but it saves a line or two :)
return ($db->GetRow($query));
After you run your getpage function, I'd strongly recommend var_dump()ing the result. Even if your function returned NULL, you'll still see this in the var_dump. If in doubt, dump it out :). I'd also recommend installing xdebug to make the var_dump output more readable.
$page = ModPages_GetPageByName($_GET['page_name']);
var_dump ($page);
I would also strongly recommending var_dumping your query before you execute just to make absolutely sure that you're running the query you think you're running. Copy and paste the outputted query into sqlyog or phpmyadmin or whatever you use for interactive access to your database and make sure it returns what you think it should return.
Other things to check, is the page you're trying to return actually set page_enabled='yes'? Does the page_enabled column actually store the value as 'yes', or is it a bool or an integer or something else? Is magic quotes enabled or disabled? If they're in one state when you think they're in the other they can cause confusion. Are errors actually being reported to the browser? Add a line at the top of your script that's guaranteed to fail just to make sure, like an attempted foreach on an integer. If you don't see an error, then maybe error reporting isn't configured properly. I know those are obvious questions but I also know how easy it is to overlook the obvious if you're not getting what you expect out of a query.
Are you sure $page is not set, or is it just that your debug instructions don't print anything? Try logging to a file or a database instead; maybe your code triggered output buffering or something like that.
Also, you are calling ModPages_GetPageByName before declaring it. That is usually okay, but might not be in special circumstances (e.g. when the code is wrapped in an if block). Try swapping the two.
Also, check your environment and disable opcode caching and other possible error sources. APC for example can call the old version of the script long after you changed the PHP file.
While some of you have put extra effort into responding to this, nobody has been able to see the full picture, even given the details I have provided. I have been unable to trace the issue back to its source, but have moved on to a different project.

Passing data from one php page to another is not working - why?

Frustrated php novice here...
I'm trying to pass a "type" value of either billto or shipto from ab.php to abp.php.
ab.php snippet:
<?php
echo '<a href="' . tep_href_link(FILENAME_ABP, 'edit=' . $bill_address['address_book_id'] . '&type=billto', 'SSL') . '">' .
tep_image_button('small_edit.gif', SMALL_IMAGE_BUTTON_EDIT) .
'</a>';
?>
This does add the &type=billto to the end of the url. It looks like this:
www.mydomain.com/abp.php?edit=408&type=billto&id=4a6524d
abp.php snippet:
if ($HTTP_GET_VARS['type'] == 'billto') {
then it does a db update...
The if returns false though (from what I can tell) because the update is not performed.
I've also tried $_GET instead of $HTTP_GET_VARS.
Because the code in abp.php isn't executed until after the user clicks a button, I can't use echos to check the value, but I can see the type in the url, so I'm not sure why it's not executing.
Could really use some direction... whether it's what I need to change, or even just suggestions on how to troubleshoot it further. I'm in the middle of a huge learning curve right now. Thanks!!!
edit:
Sorry, I just realized I left out that after the db update the user goes back to ab.php. So the whole workflow is this:
User goes to ab.php.
User clicks link to go to abp.php.
User changes data on abp.php.
User clicks button on abp.php.
Update to db is executed and user is sent back to ab.php.
Because the code in abp.php isn't executed until after the user clicks a button, I can't use echos to check the valueWhy not?
echo '<pre>Debug: $_GET=', htmlspecialchars(var_export($_GET, true)), "</pre>\n";
echo '<pre>Debug: billto===$_GET[type] = ', 'billto'===$_GET['type'] ? 'true':'false', "</pre>\n";
if ( 'billto'===$_GET['type'] ) {
...
edit: You might also be interested in netbeans and its php module:
"Debug PHP code using Xdebug: You can inspect local variables, set watches, set breakpoints, and evaluate code live. Navigate to declarations, types and files using Go To shortcuts and hypertext links."
try something like this
if ($_GET['type'] == 'billto') {
die("got to here, type must == billto");
this will prove that your if statement is working or not,
it may be that the update part is not working
Before the if statement - try
var_dump($_GET);
And make sure the 'billto' is contained within the $_GET array. Of course, if you have got the debuger setup, you should be able to watch the value of the $_GET array
or try:
var_dump($_REQUEST);
Check the URL of the second page, is it in the correct form? From the code snippet you post, I don't know if there would be a ? after the question mark. Also try to disable the redirect to see if your code is working as it should.
One other thing is you may want to put the new url in a variable first, then put that into the link HTML. It's less efficient, but makes the code easier to read and debug.
Try turning on error reporting, place this at the start of your php script
error_reporting ( E_ALL | E_STRICT)
PHP is very tolerant of typos and accessing subscripts in an array that does not exist; by enforcing strict and reporting all errors you would be able to catch those cases.
If you can't see the output, try this:
function log_error($no,$msg,$file,$line)
{
$errorMessage = "Error no $no: $msg in $file at line number $line";
file_put_contents("errors_paypal.txt",$errorMessage."\n\n",FILE_APPEND);
}
set_error_handler('log_error');
You may have to set some file permissions for the log file to be written to.
Of course, you can get Netbeans and its debugging module too.

Categories