Getting Fatal Error in get_results of WordPress - php

<?php
if (isset($_GET['confirm_code'])) {
__construct();
}
function __construct() {
global $wpdb;
$table_one = $wpdb->prefix . "fantasticemailnewsletter_temp";
$confirm = $_GET['confirm_code'];
$mylink = $wpdb->get_results("SELECT * FROM $wpdb->$table_one WHERE confirm_code = $confirm");
if ($mylink) {
echo $mylink->confirm_code;
echo "success";
echo $wpdb->show_error();
} else {
echo "You Subscription is not process right now please try again later";
}
}
?>
I’m trying to create a newsletter plugin in WordPress. I make a confirmation link for the corresponding subscriber to prevent spammers, creating a random key for every subscription e-mail. I pass the random key with query string through mail like this:
http://www.example.com/wp-content/plugins/plugininname/includes/subscriber.php?confirm_code=%2248c9c7d48165379b49f58962c0092466%22
In subscriber.php only, I’m using the above code, but for some reason, there’s an error at get_results():
Fatal error: Call to a member function get_results() on a non-object
How can I overcome this prob.

The error looks like the object of wpdb hasn't been instantiated.
Generally a method of a class shall be called after an object has been instantiated, if the method is not a static one. Otherwise this error shows.
I would check other parts of code or the file to see whether it's executed before WP code.
For example, if the file isn't a plugin or a theme (which means the file stands alone) and you haven't properly called WP framework header file before executing this file, the $wpdb object may not have been instantiated. I would definitely try the code by #Rikesh in the comment of your question.

you dont need to redeclare wpdb in query $wpdb-> as you already declared in this line $table_one = $wpdb->prefix . "fantasticemailnewsletter_temp";
<?php
if(isset($_GET['confirm_code'])) {
__construct();
}
function __construct() {
global $wpdb;
$confirm = $_GET['confirm_code'];
$mylink = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}fantasticemailnewsletter_temp WHERE confirm_code = $confirm");
if($mylink) {
echo $mylink->confirm_code;
echo "success";
echo $wpdb->show_error();
}
else {
echo "You Subscription is not process right now please try again later";
}
}
?>

$query = $wpdb->query("SELECT * FROM $wpdb->$table_one WHERE confirm_code = $confirm");
$mylink = $wpdb->get_results($query);

Related

PHP Function not available on another page

I am trying to get a function to output on a page on my site.
All my functions are in functions.php, which I include in the head on all pages.
Here is an example function:
function get_username(){
$userID = $_SESSION['user'];
if($userID){
$username = mysqli_query($dbconfig,"SELECT * FROM users WHERE userId='$userID'");
while($row = mysqli_fetch_assoc($username)) {
return $row['userName'];
}
}
}
When calling the function get_username nothing is returned. To verify, I print the session to check the data exists, which it does.
I have also tried just echoing a simple word in the function like this:
function get_username(){
echo 'test';
}
Again nothing is outputted. As mentioned above the functions.php is included in the head of the page.
Any ideas?

Fatal error: Call to undefined function wp_update_user()

I've written a function to change the role of a member in response to a Membermouse push notification. The code fails with the message "Fatal error: Call to undefined function wp_update_user()...". This implies the function has not been called but the folder is in the WP environment and is called by a WP Plugin function. Although its not advised, I tried various ways to require the user.php file (where wp_update_user is located) in the code and none worked. I'm at a loss since I believe the code is correctly written but I'm not even sure about that at this point. The custom script file (below) is in a custom folder in the root directory.
<?php
// Custom script to change a members role to Spectator upon cancellation
if(!isset($_GET["event_type"])) {
// event type was not found, so exit
echo "Exit";
exit;
} else {
$status = $_GET["status"];
if($status == 2) {
$eventType = $_GET["event_type"];
$user_id = $_GET["member_id"];
$newrole = "bbp_spectator";
$user_id = wp_update_user( array(
'ID' => $user_id,
'role' => $newrole
) );
if (is_wp_error($user_id)) {
// There was an error, probably that user doesn't exist.
echo "Error";
} else {
// Success!
echo "Role Changed to Spectator";
}
}
}
?>
https://codex.wordpress.org/Plugin_API/Action_Reference. If you just include without an action hook that runs after the user is set (init is a good one), then there is no user and the function doesn't exist yet.
function prefix_my_function_name() {
//your code
}
add_action( 'init' , 'prefix_my_function_name' );
I fixed it... I was using the wrong path for the require statement. I love the help on the web, but the multitude of responses on various forums shows so many ways to do things. It never occurred to me to keep it simple. I added the following to the top of the code:
require_once("wp-includes/user.php");
All the comments from previous posts with similar problems were proposing various ways of saying the same thing but this one worked.

Cannot fetch array inside a function PHP

I can't fetch an array inside a function but I can do it outside of the function. When I fetched it outside the function and echo it out, it prints out 1, but inside the function, using the same fetch array codes and echoing it out, it echos as null. I can tell because the --- symbols echos out, but the number 1 doesn't. I'm confused, because if it worked outside the function, the same code should work inside a function, right? Unless I'm doing something wrong? Please help. Thanks.
<?php
include('connect.php');
include('username.php');
//include('functionGet.php');
$boo = $_GET['boo'];
echo "$boo";
function getData($select,$from,$where,$equals){
$fetch = mysql_fetch_array(mysql_query("SELECT acceptedChallenges FROM
userLogin WHERE username = '$username'"));
$fetch = $fetch['acceptedChallenges'];
echo "---$fetch---";
}
if($boo = 'yes'){
$acceptedChallenges =
getData("acceptedChallenges","userLogin","username",$username);
$fetch = mysql_fetch_array(mysql_query("SELECT acceptedChallenges FROM
userLogin WHERE username = '$username'"));
$fetch = $fetch['acceptedChallenges'];
echo "$acceptedChallenges$username$fetch";
//mysql_query("UPDATE userLogin SET openChallenges = '0' WHERE username =
'$username'");
//mysql_query("UPDATE userLogin SET acceptedChallenges =
'$acceptedChallenges' WHERE username = '$username'");
}
else{
}
?>
you are passing $where instead of $username so change
function getData($select,$from,$where,$equals){
to
function getData($select,$from,$username,$equals){
You're using $username in your query, but there's no such variable in your function:
function getData($select,$from,$where,$equals){
$fetch = mysql_fetch_array(mysql_query("SELECT acceptedChallenges FROM
userLogin WHERE username = '$username'"));
$fetch = $fetch['acceptedChallenges'];
echo "---$fetch---";
}
In regards to the discussion in comments, here's a clip to demonstrate variable scope:
$username = "Testing";
function test1() {
echo $username; // Will emit Notice, since $username is undefined
}
function test2() {
global $username;
echo $username; // Will work, but this is bad practice
}
function test3($username) {
echo $username; // This is the proper way to do it
}
test1();
test2();
test3($username);
You can play with it here.
This code souns very bad:
Dont eval string with the variable if ouy have the variable echo $boo;
Don't use eval string ", use non eval ' and concat variables
Put globales off and escape the variables before query to prevent injection mysql_real_escape
Do a class to abstract data, not a function
Use non deprecated connect db functions like mysqli or pdo
Don't use static funcions to connect, use an instance of the library and his methods, is clear and more simple $db=new Mysqli()
Don't concat 2 or 3 functions, set the result in a variable and continue in a next line.
Iterate the result of fetch with if or while depending you have one or more results, don't get the result directly
Don't close php tag if you only have php
I suggest:
Set globales off if you have on in your php (show if on with phpinfo()
Create a instance of database using PDO library $db=new PDO()...
Create a class to get database information for everhy entity for example ChallengeObject with a method to get information function get($user)
Instance the ChallengeObject and pass to the constructor the database connection instance.
Inside get() function use prepared statements to pass data and prevent injection
private databse;
function __construct($database) {
$this->databse=$databse;
}
function get($user) {
$sql='SELECT acceptedChallenges FROM userLogin WHERE username = :user';
$this->database->prepare($sql)
$this->database->bindParam(":user",$user,'PDO::INT_VALUE);
$this->database->execute();
if ($user=$this->databse->fetch()) {
return $user;
}
return false;
}
<?php
$database=new PDO(...);
$challengeObject=new ChallengeObject($database);
$user=$challengeObject->get($_POST['boo']);
if ($user!=false) {
echo "Authenticated successfull";
}

PHP session being lost

I'm trying to implement and authentication system with jQuery and PHP. All the php work is made in the controller and datahandler class. There is no php code inside the .html files, all the values in .html files are rendered via jQuery that request the data from php server. So what I'm trying to do is:
When user clicks the login button, the jQuery makes a call to the authenticate() method in my controller class, it checks if the user is correct and stuff, and if it is, start the session and set the user_id on the session so I can access it later, and returns the userId to the jQuery client again.
After that, if everything is fine, in jQuery I redirect it to the html file. On the html file I call a jQuery from the <script> tag that will handle other permissions. But this jQuery will access the method getPermissionString (from the same class of authenticate() method mentioned before), and it will need to get the session value set in authenticate method.
The Problem:
When I try to get the session value inside getPermissionString() it says:
Notice: Undefined variable: _SESSION
I've tried to check if the session is registered in the second method, but looks like it's not. Here is my PHP code.
Any idea? Thanks.
public function authenticate($login, $password)
{
$result = $this->userDataHandler->authenticateUser($login, $password);
if(is_numeric($result) && $result != 0)
{
session_start();
$_SESSION["uid"] = $result;
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
echo $result;
}
else
{
echo 0;
}
}
public function getPermissionString()
{
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
}
Before you can access $_SESSION in the second function you need to ensure that the program has called session_start() beforehand. The global variable is only populated when the session has been activated. If you never remember to start a session before using it then you can change the php.ini variable below:
[session]
session.auto_start = 1
Further, you said that you're using a class for your code. In this case you can also autos tart your session each time the class in created by using magic methods:
class auth {
function __construct() {
session_start();
}
function yourfunction() {
...
}
function yoursecondfunction(){
...
}
}
If you don't have session.auto_start enabled, and authenticate and getPermissionString are called on two different requests, you need to call session_start() in each function.
If you need more information on how the session ID is passed, just read Passing the Session ID
You should not use that function if session is not started. So throw an exception:
public function getPermissionString()
{
if (session_status() !== PHP_SESSION_ACTIVE)
{
throw new Exception('No active session found.');
}
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
}
This ensures the pre-conditions of your functions are checked inside the function so you don't need to check it each time before calling the function.
You will now see an exception if you wrongly use that function and it will give you a backtrace so you can more easily analyze your code.
For php sessions to work you have to call session_start() every time you script is requested by the browser.

How to replace "Login" button with user name in CodeIgniter

I'm trying to create a universal header for a website built on CodeIgniter, and I'm having trouble figuring out the code that will switch the 'Login' link for the user's name (with a link to the profile page) after the user logs in.
In the controller functions, I've tried the following code:
if(!$this->session->userdata($userSessionVar))
{
$data['header_output'] = "<li><a href='" . base_url() . "index.php/main/login'>Login</a></li>";
} else
{
$data['header_output'] = $this->session->data('userFirstName');
}
(I realize this is incomplete, based on my designs, but it's just to test.) $userSessionVar holds the value "logged in" once logged in. Probably not the best way to do that. And that doesn't seem to work (and I pass the $data to the view). I've also tried making a custom function:
function check_login()
{
$CI =& get_instance();
$userSessionVar = 'logged_in';
if( ! $CI->session->userdata($userSessionVar))
{
return false;
} return true;
}
And then use the true/false return to structure the $header_output variable. None of these seem to work. I'm new to CodeIgniter and have some intermediate level of PHP/HTML/CSS, etc. I'm sure I'm missing something obvious and would appreciate any help, as well as a heads-up on how to avoid including the code in every controller function.
The variable $userSessionVar is only available within the function check_login(), so when you try to use it outside of the function, it will be blank (and therefore useless).
I recommend that you simply use $this->session->userdata('logged_in') and $CI->session->userdata('logged_in') rather than using the variable $userSessionVar to store what appears to be a constant value.
Also, you have an error in your code. You need to replace $this->session->data('userFirstName') with $this->session->userdata('userFirstName')
Here's how I typically deal with user data. First, add auth.php to the models folder:
<?php
class Auth extends Model {
private $user_data = false;
function Auth() {
parent::Model();
if ($this->input->post('action') == 'login') $this->login();
else if ($auth_id = $this->session->userdata('auth_id')) {
$user = // load user data from the database into the variable $user
if ($user) {
$this->user_data = $user;
} else $this->session->unset_userdata('auth_id');
}
}
function login() {
// process POST, check with database, and then store user_id using
// $this->session->set_userdata('auth_id', $user_id_here)
}
function me() {
return $this->user_data? (object)$this->user_data : false;
}
}
?>
Then, auto-load the model. To do this, edit config/autoload.php like so:
$autoload['model'] = array('auth');
Now your IF statement could look like this:
if ($me = $this->me()) $data['header_output'] = $me->userFirstName;
else $data['header_output'] = '<li>Login</li>';
in your model auth.php you've got the statements
class Auth extends Model
and
parent::Model();
With CodeIgniter, should these not be "CI_Model"...?

Categories