Working with PHP global variable - php

I am trying to integrate my regular php build script into wordpress. I am stuck in a place where the function works perfectly before, but not in wordpress environment.
In the code below, I am getting blank array in my ajax request whereas I do have results inside myFunc (I have tested by putting wp_send_json inside).
Do I need to change anything to work with PHP globals in wordpress?
$final = array();
function myFunc(){
global $wpdb;
global $final;
$sql = 'SELECT .......';
$result = $wpdb->get_results($sql);
if($wpdb->num_rows > 0){
foreach ( $result as $row ) {
$final[] = $row->pdate;
}
return true;
}
return false;
}
myFunc();
wp_send_json($final);

You can use following statements to get updated value from function.
$arr = array();
function myFunc($new_arr){
global $wpdb;
$sql = 'SELECT .......';
$result = $wpdb->get_results($sql);
if($wpdb->num_rows > 0){
foreach ( $result as $row ) {
$new_arr[] = $row->pdate;
}
}
//It will return updated array if result having rows.Otherwise return empty array.
return $new_arr;
}
$final = myFunc($arr);
if(!empty($final))//if block will be execute if myFunc doesn't return empty array.
{
wp_send_json($final);
}

That should work but globals are nasty things to use and will often conflict I'd suggest just returning the array from the function.
e.g.
function myFunc(){
global $wpdb;
$final = array();
$sql = 'SELECT .......';
$result = $wpdb->get_results($sql);
if($wpdb->num_rows > 0){
foreach ( $result as $row ) {
$final[] = $row->pdate;
}
return $final;
}
return false;
}
$myFuncReturn = myFunc();
if($myFuncReturn !== false){
wp_send_json($myFuncReturn);
}

Related

moved working routine to function, now results are not present

As I try to consolidate my code and make it more available to other projects, I've run into a problem:
variables that were generated and available are not anymore when that routine is moved to a function:
This is the query:
$count = "SELECT eid, Count, Name, name2, Email, pay FROM h2018";
THIS WORKS FINE:
$result = $mysqli->query($count);
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$$key = $value;
echo($a." and ".$value."<BR>");
}
NOT WORKING FINE:
function avar($result) {
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$$key = $value;
}
}
$result = $mysqli->query($count);
avar($result);
echo($a." and ".$value."<BR>");
I thought the variable variables would be available from outside of the function. I tried doing a return, but that didn't help. I also tried to global $$key, but that didn't work either.
What am I doing wrong?
There is multiple mistakes or missing steps like return or array
function avar($result) {
$data=array();
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$data[$key] = $value;//if there is multiple records then used array otherwise you should used variable
}
return $data;
}
$result = $mysqli->query($count);
$data=avar($result);//get return value
print_r($data);
Please, read the PHP documentation about the Variable Scope for more information. The variables inside your function are local so you cannot access them outside of your function. You would have to return something.
For example, this could work:
function avar($result) {
$resultArray = false;
$row = $result->fetch_assoc();
foreach ($row as $key => $value) {
$resultArray = [
'key' => $key,
'value' => $value
];
}
return $resultArray;
}
$result = $mysqli->query($count);
$queryResult = avar($result);
if ($queryResult) {
echo 'Key: ' . $queryResult['key'] . ' | Value: ' . $queryResult['value'];
}
Please do note that fetch_assoc will return an array with multiple items if there is more than one result. In my example only one (and the last) result will be returned.
Edit: As #Nigel Ren said in his comment. In this case you're basically rebuilding an array which is going to look (nearly) the same as the array which is being returned by fetch_assoc, which is pointless. My function can be used if you want to add conditions in the future, or manipulate some data. Otherwise, don't use a function and just use the results from fetch_assoc.

N1QL prepared statement not working 100%

I have a problem where some variables are probably (I can't know for sure) not inserted into the final statement. Here is my example:
Works:
public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
$query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND TOSTRING('.$field.') LIKE "%'.$searchterm.'%" ORDER BY `_id` limit $limit offset $offset');
$query->options['$collection'] = static::COLLECTION_NAME;
//$query->options['$field'] = $field;
$query->options['$limit'] = $recordsPerPage;
$query->options['$offset'] = $recordsPerPage*($page-1);
//$query->options['$searchterm'] = $searchterm;
$result = DB::getDB()->query($query);
var_dump($query);
var_dump($result);
$objects = array();
foreach($result as $row) {
$object = new static($row->{"public_portal"});
$object->setId($row->{"public_portal"}->{"_id"});
$objects[] = $object;
}
//var_dump($objects);
return $objects;
return $result;
}
Debug Output:
debug01
Does not work:
public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
$query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND TOSTRING($field) LIKE "%$searchterm%" ORDER BY `_id` limit $limit offset $offset');
$query->options['$collection'] = static::COLLECTION_NAME;
$query->options['$field'] = $field;
$query->options['$limit'] = $recordsPerPage;
$query->options['$offset'] = $recordsPerPage*($page-1);
$query->options['$searchterm'] = $searchterm;
$result = DB::getDB()->query($query);
var_dump($query);
var_dump($result);
$objects = array();
foreach($result as $row) {
$object = new static($row->{"public_portal"});
$object->setId($row->{"public_portal"}->{"_id"});
$objects[] = $object;
}
//var_dump($objects);
return $objects;
return $result;
}
Debug output:
debug02
Basically the second example returns no result, while the first one works just fine.
Any idea why?
You are not using N1QL parameters correctly. You must decide if you are evaluating your parameters in PHP or in N1QL.
The field name cannot be a N1QL parameter, so you evaluate it in PHP:
TOSTRING('.$field.') LIKE ...
The search term should be a N1QL parameter, so you add wildcards in PHP and then pass it to N1QL as a parameter:
$searchterm = '%'.$searchterm.'%'
TOSTRING('.$field.') LIKE $searchterm ...

PDO ForEach Loop in array (PHP)

I want to have all results from my database in one array
my function:
function GetWinkelProduct($g_Winkel) {
global $g_Conn;
$l_Stmt = $g_Conn->prepare("SELECT pd_id FROM `producten_:Winkel`");
$l_Stmt->bindValue(':Winkel', $g_Winkel, PDO::PARAM_INT);
$l_Stmt->execute();
$l_qurries = new dbquery();
$l_LastProduct = $l_qurries->GetLastProduct($g_Winkel);
while($l_Row = $l_Stmt->fetch(PDO::FETCH_ASSOC)){
$out = array();
foreach($l_Row as $product){
$out[] = $product['pd_id'];
}
}
return $out;
}
other page: <?php print_r($l_qurries->GetWinkelProduct($g_Winkel)); ?>
only I get the first result in the array and when I do $product['pd_id'] I get only the last result.
Try this...
Change fetch to fetchAll in while loop and renove foreach inside while loop
function GetWinkelProduct($g_Winkel) {
global $g_Conn;
$l_Stmt = $g_Conn->prepare("SELECT pd_id FROM `producten_:Winkel`");
$l_Stmt->bindValue(':Winkel', $g_Winkel, PDO::PARAM_INT);
$l_Stmt->execute();
$l_qurries = new dbquery();
$l_LastProduct = $l_qurries->GetLastProduct($g_Winkel);
while($l_Row = $l_Stmt->fetchAll(PDO::FETCH_ASSOC)){
$out = array();
$out[] = $l_Row ['pd_id'];
}
return $out;
}
ref:http://php.net/manual/en/pdostatement.fetchall.php
You must initialize the array outside the while loop and you don't need the foreach.
that way you are creating a new array every time the while iterates, that way you end up replacing the array.
$out = array();
while($l_Row = $l_Stmt->fetchAll(PDO::FETCH_ASSOC)){
$out[] = $l_Row['pd_id'];
}
return $out;

PHP Reference for MySQL query

My function:
function sql_query($s, $x) {
$query = mysql_query($s);
global $mysql;
while($mysql = mysql_fetch_array($query)) {
return;
}
}
Now it's work only with $mysql variable:
echo $mysql['username'];
How to make it works only with:
sql_query("select * from users where id = '1' limit 1", "varname");
$varname['username'];
I want to set a SQL Query and Variable name in function, like:
sql_query("sqlquery", "variable");
echo $variable['id'];
Thanks for reply!
function sql_query($s, &$x) {
global $mysql;
$query = mysql_query($s);
$result = mysql_fetch_array($query);
foreach($result as $key => $value) {
$x[$key] = $value;
}
}
This should assign each variable that is returned by the query to a key in array $x (assuming it is an array). Notice that I am passing $x by reference instead of by value, eliminating the need to return anything.

php function in a while Loop

i searched all over the web or i just don't see it.
I want to do the following:
<?php
function abc(){
$sql = "SELECT * FROM table";
$result = mysql_fetch_assoc($sql);
$data = mysql_fetch_assoc($result);
}
?>
<? while(abc()) : ?>
<?=article_title()?>
<?=article_content()?>
<?=endwhile;?>
Could somebody give me a direction and/or example?
Thank you very much
PHP does not have generator/iterator functions, so you cannot do that.
You can however return an array and iterate over that array:
function abc() {
// ...
$rows = array();
while($row = mysql_fetch_assoc($result)) { $rows[] = $row; }
return $rows;
}
foreach(abc() as $row) {
// do something
}
If the functions you call need access to the row, pass it as an argument. Using global variables for it would be very bad/nasty
have you tried to do something like that?
<?php
function getData(){
//get the data from the database
//return an array where each component is an element found
}
$elems = getData();
foreach($elems as $e){
doSomethingWith($e);
}

Categories