access php variable through concatenation - php

I was trying to achieve something simple and was wondering if it was possible. Google search proved unhelpful this time. Probably it's not possible, but I am not sure. I have the following code:
<?php
//Enter your code here, enjoy!
$query1="yay";
$query2="it";
$query3="works";
for($x=1;$x<=3;$x++){
$query="\$query".$x; //I need to assign the above variables
echo $query;
}
?>
I want the output to be "yayitworks" but instead I get "$query1$query2$query3". Is there any way to get my result? I know a switch statement will help me achieve this, but am just curious.
Thanks in advance...:-)

What you want is variable variables: http://php.net/manual/en/language.variables.variable.php
$query = ${"query".$x}

Related

PHP - show variable in while loop

I have while loop in a PHP file and outside of that, I have one variable. When I try to add this variable into while, it doesn't work.
example code:
<?
$var1 = 2999288;
while($row = mysql_fetch_array($result)){
echo $var1;
}
?>
Can anybody tell me a solution, how to echo that variable into a while? Or what I'm doing wrong?
Your SQL query is not returning any rows, make sure that your query is working properly before echoing results. Also please look into prepared SQL statements, they are more safe than the traditional way that you are using.

Print out all variables except one

In PHP, I get a dump of all variables like so:
var_dump(get_defined_vars());
However, in one particular application one of the variables is huge and I would really like to avoid printing it out. I could foreach over the get_defined_vars() array to create a new array and blacklist the problematic variable, but if there is a better way then I would love to know about it.
Thanks.
var_dump(array_diff_key(get_defined_vars(), array_flip(array('unwantedVar'))));
Hmm, could you just unset the var and var_dump() ?
unset($bigChuckNorrisVar);
var_dump(get_defined_vars());
Granted you might need to use that variable down your program after that, but that's a quick way to debug.

Transform output php

I have this, which is calling an integer value say: 2500.
echo "number_format({$row2['count(cID))";
This gives me an undesired output.
How do I fix this? How am i implementing the function wrong here? (I mean obviously I am)
If I guessed right, you want something like this:
echo number_format($row2['count(cID)']);
I suppose you are getting a column from the database and calling it 'count(cID)', but it's really hard to know what you need. Try providing more details.
Didn't you mean
echo number_format($row2[count($cId)]);
?

PHP - Looking at the Web Link

I am very curious on how to do this. I want a PHP script to look at the string after the URL link and echo the value.
For example, if I entered:
"http://mywebsite.com/script.php?=43892"
the script will echo the value 43892. I have seen this in most websites, and I think it will be a very useful to have in my application.
Thanks,
Kevin
You mean, something like
http://mywebsite.com/script.php?MyVariable=43892
? Variables provided at the end of the URL like that are available in the $_GET array. So if you visited the above URL and there was a line on the page that said
echo $_GET['MyVariable'];
then 43892 would be echoed.
Do be aware that you shouldn't trust user input like this - treat any user input as potentially malicious, and sanitise it.
echo filter_var($_SERVER['QUERY_STRING'], FILTER_SANITIZE_NUMBER_INT);
The sanitation is because in your example the query string is =43892, not 43892. The filter used "remove[s] all characters except digits, plus and minus sign".
Don't you mean http://mywebsite.com/script.php?43892 ?
You can either use apache URL rewriting or try to extract all entries from $_GET and look a the one which looks like a number or simply doesn't have a value.
Try manually parsing the URL like this
$geturl = $_SERVER['REQUEST_URI'];
$spliturl = explode("?",$geturl);
$get
= explode("=",$spliturl[0]);
echo $get[1];
:)
Before I really answer your question, I just have to say that most sites - at least that I have seen - actually use ?43892, with the =. This is also much easier than using it with = in my opinion.
So, now to the actual answer. You can simply extra the query string usingĀ $_SERVER['QUERY_STRING'].
An example:
User requests index.php?12345:
<?php
echo $_SERVER['QUERY_STRING'];
?>
Output:
12345
Note that you can also use something like
<?php
if(substr($_SERVER['QUERY_STRING'], 0, 1) == '=') {
$query_string = substr($_SERVER['QUERY_STRING'], 1);
}else{
$query_string = $_SERVER['QUERY_STRING'];
}
echo $query_string;
to support ?=12345 as well as 12345, with the same result. Note also that ?=12345 would not be available as $_GET[''] either.
The way you usualy use query parameters is by assigning them like http://mywebsite.com/script.php?var1=123&var2=234
Then you will be able to access them by $_GET['var1'] and $_GET['var2'] in your PHP script
I'de recommand parse-url for this. The documentation contains all you (I think) need.

What is the best way to capture data returned from a function in PHP?

I am new to programming and learning with Wordpress.
the_title(); //outputs the title of the page
I want to capture the title of the page into a string variable so I can manipulate it with strtolower and str_replace functions.
The only way I have gotten it to work is with output buffering.
ob_start();
the_title();
$result = ob_get_clean();
echo str_replace(" ","-",strtolower($result));
/*there has got to be an easier way....
i dont fully understand why */
str_replace(" ","-",strtolower(the_title()));
What am I doing wrong?
If what you really are looking for is the wp_title function, the 2nd argument it takes is a boolean on whether or not it should display it or return it. Pass it false so it will return it to the var, then you can do this:
$mytitle = wp_title(null, false);
Otherwise, your only option is to find the function you're looking for and modify the source code.
There is no easier way. Your function does not return the string, it prints it, therefore you will have to use output buffering if you want to capture the output.
It's the difference between f1() and f2() in the following example.
// Returns a string, prints nothing.
function f1() {
return "String";
}
// Prints a string, returns nothing.
function f2() {
echo "String";
}
Wordpress is a HORRIBLE app to learn how to program from. It uses these global functions that "just work" but they do very specific tasks "inside 'The Loop'". As I say, this is a horrible example of what good code should be.
Thankfully (for you) there are other functions that just return the part you're looking for. Rather than me just writing what you need, you can read a full listing here. Take care that you note down which must be within the mythical Loop and which you can use anywhere.
As it happens there are even more ways to get the title, but I was really imagining for this example you would do something like:
$this_post = get_post($post); // I *think* $post is the post ID inside the loop though I could be wrong
echo $this_post->post_title;
But as another poster (correctly) says you can use a fairly simple wp_title() function to grab the current loop title.
This brings me back to perhaps wanting to explain why learning programming from Wordpress is a bad idea. They have so many damned way of doing the same damned thing that it's almost impossible to keep on top of things.
A blog is a really simple set of data (even moreso in WP's case because it isn't fully normalised) but rather than just having one way to output a title <?php echo $post->title; ?> you have umpteen ways, all doing subtly different things.
If you really want to learn how to program (instead of hacking your way around the crap that is the WP internals), creating a simple blog engine is fairly quick and fun... It's certainly how a lot of people get into a new language or framework.
And if you really want to have fun, have a look at Django.
Enough of the Wordpress rant. If you're fighting something like this in the future that doesn't have 100 ways of doing it, I really wouldn't recommend output-buffer-capturing. It uses up a whole buttload of resources for something relatively simple.
The easiest way can be as simple as just taking the source for the original function, sticking it in a new function and replacing the echo with return.
Just note there may be some database connectivity to handle that returning prematurely may break... So if the echo isn't the last statement, instead of returning right there, store the string as a variable and return at the end of the function.
just figured Id share my final solution with you guys.
This was to give my body tags unique id's in wordpress.*/
$title =wp_title(null,false);
echo strtolower(str_replace(' ','-',ltrim($title)));
//without the ltrim() 2 dashes are created before the title.
Almost every 'the_*' function in Wordpress has a 'get_the_*' counterpart. So, you just have to use
echo str_replace(" ","-",get_the_title());
And it's going to work like a charm. there's also get_the_excerpt(), get_the_content() and the_permalink() which somehow breaks the naming convention (God knows how many times I've written "get_the_permalink()" and got frustrated on why it didn't work)
Cheers!

Categories