Variable via GET not working in wordpress - php

I am carrying a variable via $_GET to a page which processes the action, the variable carries over correctly but the database won't update and throws an error.
Here is my link with a varible;
echo "<td><a href='".plugins_url()."/myremovalsquote/inc/disable.php?id=".$active_partner->partner_id."' class='button-primary'>Disable</a></td>";
I then use the variable passed in my /disable.php
$id = $_GET['id'];
echo $id;
global $wpdb;
if ($commit = $wpdb->query("UPDATE partners SET active='no' WHERE partner_id='"'$id'"'")) {
echo 'Success';
} else {
echo 'Failed';
}
The echo outputs the correct string, but then I get this error message.
77
Fatal error: Call to a member function query() on a non-object in /home/myremovalsquote/public_html/wp-content/plugins/myremovalsquote/inc/disable.php on line 9

You are calling a PHP file directly without loading WordPress, so $wpdb and it's method aren't available to you.
You can fix this by including wp-load.php, however this is generally considered to be bad form, as explained in Don't include wp-load please.
A better solution would be to create an AJAX listener, and then call that from your link (it doesn't really have to be a JavaScript request or JSON response). You would need to pass in your action to call the right PHP method, along with your other variables.
// attach action "handler_33762965" to the handler_33762965() function for admin (wp_ajax_*) and front end (wp_ajax_nopriv_*)
add_action( 'wp_ajax_handler_33762965', 'handler_33762965' );
add_action( 'wp_ajax_norpriv_handler_33762965', 'handler_33762965' );
function handler_33762965(){
// make sure the ID is set before grabbing it
$id = isset( $_GET['id'] )? $_GET['id'] : 0;
// do stuff
exit();
}
Your link would look like the following.
link

Related

How can I assign a php return value without causing my sql to run twice?

I am making a wordpress plugin that deals with forms.
I have a form that upon submit, a function is called to insert the values into the DB.
From that function, I am returning the clientID value which was auto Incremented.
I then assign that returned value to a new variable in a new form on the same page.
It works, but I am getting two DB inserts now. IT seems when I assign the new Variable to the function, it runs the insert statement twice.
What I am trying to accomplish is to insert the user into the first table within a function and return just the Clients ID so I can than use the ID for another table insert.
Any help would be appreciated.
The form which on submit calls the function to insert into DB
<form action="" id="new_client_form" method="POST" onsubmit="return submit_new_client()">
The function which contains DB code and returns Client ID
function submit_new_client () {
if (isset($_POST['submit'])) {
/////
$insertClient = $db -> exec("INSERT INTO client SET .......");
$clientId = $db -> lastInsertId();
echo $clientId .'Is the New client ID';//This is printing the correct ID(used for testing)
}
return $clientId;
}
add_action('init', 'submit_new_client');
The new form/ Where I assigned the variable to the function
<?php
$client = submit_new_client();
if(isset($_POST['submit'])) {
echo "<p>The Client Id is</p>";
echo "$client";
} else {
echo "<p>No client ID</p>";
}
?>
For example, Once the form is submitted I will get an Echo from the function saying the Client ID is 32. But when I go down to the next form it will say the Client ID is 33.
First off, in the HTML form, you have onsubmit="return submit_new_client(). The onsubmit attribute is used to call a Javascript function, not a PHP function, so I'm surprised the PHP function is being called at all.
Is it possible for you to post the code in its entirety?
Edit: I did a brief search on the add_action function you're calling. Are you sure that this call isn't calling your submit_new_client() function at some point? See the documentation I found here: https://codex.wordpress.org/Function_Reference/add_action

Get content after question mark in PHP

I am getting a request like this and the url looks like this : www.site.com/test.php?id=4566500
Now am trying to get the id number to make the code in test page work, is there a way to do this?
<?php
echo("$id"+500);
?>
You can access these values via the $_GET array:
<?php
echo($_GET['id'] + 500);
?>
This is basic PHP. You want to use the $_GET superglobal:
echo $_GET['id'] + 500;
Do not forget to check the right setting of your Getter parameter:
if (isset($_GET['id']) && preg_match("\d+", $_GET['id'])) {
// do something with $_GET['id']
} else {
// appropriate error handling
}
Remember that anyone can set the id parameter to any value (which can lead to possible XSS attacks).
You cannot access direct url parameter without using predefined PHP super global variable like $_GET["$parameter"] OR $_REQUEST["$parameter"].
So for : www.site.com/test.php?id=4566500
<?php
$id = (int)$_GET['id']; // Or $_REQUST['id'];
if(is_numeric($id)){
echo $id + 500;
}else{
echo $id;
}
?>
For more detail :
PHP $_GET Reference
PHP $_REQUEST Reference

HREF to call a PHP function and pass a variable?

Is it possible to create an HREF link that calls a PHP function and passes a variable along with it?
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='search($id)' >$name</a>";
}
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
You can do this easily without using a framework. By default, anything that comes after a ? in a URL is a GET variable.
So for example, www.google.com/search.html?term=blah
Would go to www.google.com/search.html, and would pass the GET variable "term" with the value "blah".
Multiple variables can be separated with a &
So for example, www.google.com/search.html?term=blah&term2=cool
The GET method is independent of PHP, and is part of the HTTP specification.
PHP handles GET requests easily by automatically creating the superglobal variable $_GET[], where each array index is a GET variable name and the value of the array index is the value of the variable.
Here is some demo code to show how this works:
<?php
//check if the get variable exists
if (isset($_GET['search']))
{
search($_GET['search']);
}
function Search($res)
{
//real search code goes here
echo $res;
}
?>
Search
which will print out 15 because it is the value of search and my search dummy function just prints out any result it gets
The HTML output needs to look like
anchor text
Your function will need to output this information within that format.
No, you cannot do it directly. You can only link to a URL.
In this case, you can pass the function name and parameter in the query string and then handle it in PHP as shown below:
print "<a href='yourphpscript.php?fn=search&id=$id' >$name</a>";
And, in the PHP code :
if ($_GET['fn'] == "search")
if (!empty($_GET['id']))
search($id);
Make sure that you sanitize the GET parameters.
No, at least not directly.
You can link to a URL
You can include data in the query string of that URL (<a href="myProgram.php?foo=bar">)
That URL can be handled by a PHP program
That PHP program can call a function as the only thing it does
You can pass data from $_GET['foo'] to that function
Yes, you can do it. Example:
From your view:
<p>Edit
Where 1 is a parameter you want to send. It can be a data taken from an object too.
From your controller:
function test($id){
#code...
}
Simply do this
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='?search=" . $id . "' > " . $name . "</a>";
}
}
if (isset($_REQUEST['search'])) {
search($_REQUEST['search']);
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
Also make sure that your $json_output is accessible with is the sample() function. You can do it either way
<?php
function sample(){
global $json_output;
// rest of the code
}
?>
or
<?php
function sample($json_output){
// rest of the code
}
?>
Set query string in your link's href with the value and access it with $_GET or $_REQUEST
<?php
if ( isset($_REQUEST['search']) ) {
search( $_REQUEST['search'] );
}
function Search($res) {
// search here
}
echo "<a href='?search='" . $id . "'>" . $name . "</a>";
?>
Yes, this is possible, but you need an MVC type structure, and .htaccess URL rewriting turned on as well.
Here's some reading material to get you started in understanding what MVC is all about.
http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
And if you want to choose a sweet framework, instead of reinventing the MVC wheel, I highly suggest, LARAVEL 4

PHP - include a php file and also send query parameters

I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.
if(condition here){
include "myFile.php?id='$someVar'";
}
Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.
Can someone please tell me how to achieve this?
Thanks.
Imagine the include as what it is: A copy & paste of the contents of the included PHP file which will then be interpreted. There is no scope change at all, so you can still access $someVar in the included file directly (even though you might consider a class based structure where you pass $someVar as a parameter or refer to a few global variables).
You could do something like this to achieve the effect you are after:
$_GET['id']=$somevar;
include('myFile.php');
However, it sounds like you are using this include like some kind of function call (you mention calling it repeatedly with different arguments).
In this case, why not turn it into a regular function, included once and called multiple times?
An include is just like a code insertion. You get in your included code the exact same variables you have in your base code. So you can do this in your main file :
<?
if ($condition == true)
{
$id = 12345;
include 'myFile.php';
}
?>
And in "myFile.php" :
<?
echo 'My id is : ' . $id . '!';
?>
This will output :
My id is 12345 !
If you are going to write this include manually in the PHP file - the answer of Daff is perfect.
Anyway, if you need to do what was the initial question, here is a small simple function to achieve that:
<?php
// Include php file from string with GET parameters
function include_get($phpinclude)
{
// find ? if available
$pos_incl = strpos($phpinclude, '?');
if ($pos_incl !== FALSE)
{
// divide the string in two part, before ? and after
// after ? - the query string
$qry_string = substr($phpinclude, $pos_incl+1);
// before ? - the real name of the file to be included
$phpinclude = substr($phpinclude, 0, $pos_incl);
// transform to array with & as divisor
$arr_qstr = explode('&',$qry_string);
// in $arr_qstr you should have a result like this:
// ('id=123', 'active=no', ...)
foreach ($arr_qstr as $param_value) {
// for each element in above array, split to variable name and its value
list($qstr_name, $qstr_value) = explode('=', $param_value);
// $qstr_name will hold the name of the variable we need - 'id', 'active', ...
// $qstr_value - the corresponding value
// $$qstr_name - this construction creates variable variable
// this means from variable $qstr_name = 'id', adding another $ sign in front you will receive variable $id
// the second iteration will give you variable $active and so on
$$qstr_name = $qstr_value;
}
}
// now it's time to include the real php file
// all necessary variables are already defined and will be in the same scope of included file
include($phpinclude);
}
?>
I'm using this variable variable construction very often.
The simplest way to do this is like this
index.php
<?php $active = 'home'; include 'second.php'; ?>
second.php
<?php echo $active; ?>
You can share variables since you are including 2 files by using "include"
In the file you include, wrap the html in a function.
<?php function($myVar) {?>
<div>
<?php echo $myVar; ?>
</div>
<?php } ?>
In the file where you want it to be included, include the file and then call the function with the parameters you want.
I know this has been a while, however, Iam wondering whether the best way to handle this would be to utilize the be session variable(s)
In your myFile.php you'd have
<?php
$MySomeVAR = $_SESSION['SomeVar'];
?>
And in the calling file
<?php
session_start();
$_SESSION['SomeVar'] = $SomeVAR;
include('myFile.php');
echo $MySomeVAR;
?>
Would this circumvent the "suggested" need to Functionize the whole process?
I have ran into this when doing ajax forms where I include multiple field sets. Taking for example an employment application. I start out with one professional reference set and I have a button that says "Add More". This does an ajax call with a $count parameter to include the input set again (name, contact, phone.. etc) This works fine on first page call as I do something like:
<?php
include('references.php');`
?>
User presses a button that makes an ajax call ajax('references.php?count=1'); Then inside the references.php file I have something like:
<?php
$count = isset($_GET['count']) ? $_GET['count'] : 0;
?>
I also have other dynamic includes like this throughout the site that pass parameters. The problem happens when the user presses submit and there is a form error. So now to not duplicate code to include those extra field sets that where dynamically included, i created a function that will setup the include with the appropriate GET params.
<?php
function include_get_params($file) {
$parts = explode('?', $file);
if (isset($parts[1])) {
parse_str($parts[1], $output);
foreach ($output as $key => $value) {
$_GET[$key] = $value;
}
}
include($parts[0]);
}
?>
The function checks for query params, and automatically adds them to the $_GET variable. This has worked pretty good for my use cases.
Here is an example on the form page when called:
<?php
// We check for a total of 12
for ($i=0; $i<12; $i++) {
if (isset($_POST['references_name_'.$i]) && !empty($_POST['references_name_'.$i])) {
include_get_params(DIR .'references.php?count='. $i);
} else {
break;
}
}
?>
Just another example of including GET params dynamically to accommodate certain use cases. Hope this helps. Please note this code isn't in its complete state but this should be enough to get anyone started pretty good for their use case.
You can use $GLOBALS to solve this issue as well.
$myvar = "Hey";
include ("test.php");
echo $GLOBALS["myvar"];
If anyone else is on this question, when using include('somepath.php'); and that file contains a function, the var must be declared there as well. The inclusion of $var=$var; won't always work. Try running these:
one.php:
<?php
$vars = array('stack','exchange','.com');
include('two.php'); /*----- "paste" contents of two.php */
testFunction(); /*----- execute imported function */
?>
two.php:
<?php
function testFunction(){
global $vars; /*----- vars declared inside func! */
echo $vars[0].$vars[1].$vars[2];
}
?>
Try this also
we can have a function inside the included file then we can call the function with parametrs.
our file for include is test.php
<?php
function testWithParams($param1, $param2, $moreParam = ''){
echo $param1;
}
then we can include the file and call the function with our parameters as a variables or directly
index.php
<?php
include('test.php');
$var1 = 'Hi how are you?';
$var2 = [1,2,3,4,5];
testWithParams($var1, $var2);
Your question is not very clear, but if you want to include the php file (add the source of that page to yours), you just have to do following :
if(condition){
$someVar=someValue;
include "myFile.php";
}
As long as the variable is named $someVar in the myFile.php
I was in the same situation and I needed to include a page by sending some parameters... But in reality what I wanted to do is to redirect the page... if is the case for you, the code is:
<?php
header("Location: http://localhost/planner/layout.php?page=dashboard");
exit();
?>

PHP - Dealing with GET and POST arrays

In my webapp I have a page called display.php. The script in this page behaves in different ways depending on POST and GET array content/existence, let's say: If I call this page and GET array isset, the script'll load a record using $_GET['id'], in another case, if no GET isset but isset a ceratin POST key the script'll load a random record from the DB... and so on.
At the top of my page I've added this simple(trivial) code:
//random loading
if(!isset($_GET['id']) && !isset($_POST["MM_update"])){
##
$fresh_call=true;
$saving_call=false;
$pick_a_call=false;
##
$_SESSION['call_id']=time().$_GET['operatore'];
$call_id=$_SESSION['call_id'];
//I need to load a specified record
}else if (isset($_GET['id']) && !isset($_POST["MM_update"])) {
##
$pick_a_call=true;
$saving_call=false;
$fresh_call=false;
##
$_SESSION['call_id']=$_GET['id'];
$call_id=$_SESSION['call_id'];
//update the record
}else if (!isset($_GET['id']) && isset($_POST["MM_update"])){
##
$saving_call=true;
$pick_a_call=false;
$fresh_call=false;
##
$call_id=$_POST['call_id'];
}
In display.php there's also a form that self-post data to display.php for record update (last condition in the code).
In rest of the script I'm checking $fresh_call, $saving_call, $pick_a_call values to query the db with the right UPDATE/INSERT/SELECT SQL.
I'm not sure about my solution, I would like to design a class that can help me making my script more "clear" and lighter. I think also that this situation is probably a typical problem to solve in PHP coding.
Here's a functional alternative which should work the same as the code you posted, but may be a little easier to understand:
function set_call_id( $val )
{
$_SESSION['call_id'] = $val;
}
if( isset($_GET['id']) )
{
set_call_id( $_GET['id'] );
pick_a_call();
}
else if( isset($_POST["MM_update"]) )
{
set_call_id( $_POST['call_id'] );
saving_call();
}
else
{
set_call_id( time() . $_GET['operatore'] );
fresh_call();
}
It's not part of the script you have posted, but I think the most important thing you need to do is make sure you are first escaping your GET/POST vars before using them to query the database.
For example, if you are using MySQL, you could use mysql_real_escape_string().

Categories