PHP Reference for MySQL query - php

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.

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 ...

Working with PHP global variable

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);
}

get array values with a function in PHP

What is the proper way to create a function to get array values from a query? I am getting "Undefined index: page_title" error.
However I can get the value without function like: echo $row->page_title;
Or echo $query[0]->title;
function get_page($id) {
$db = new DB();
$query = $db->get_rows("SELECT * FROM pages WHERE id = :id ", array('id' => $_GET['id']) );
foreach ($query as $row) {
$page_id = $row->id;
$page_title = $row->title;
}
return $query;
}
$page = get_page(1);
echo $page['page_title'];
here is my database class:
function get_rows($query, $values=array(), $fetchType = FETCH_OBJ)
{
$sth = $this->dbh->prepare($query);
if(is_array($values) && (sizeof($values) > 0))
{
foreach($values as $key=>$val)
{
$key = is_numeric($key) ? ($key + 1) : $key;
$sth->bindValue($key,$val);
}
}
if($sth->execute())
return $sth->fetchAll($fetchType);
}
To make the function reusable, I would rewrite it the following way
function get_page($id, $col) {
$db = new DB();
$query = $db->prepare('SELECT * FROM pages WHERE id = :id');
$query->execute(array(':id' => $id));
$results = $query->fetch(PDO::FETCH_NUM);
return $results[0][$col];
}
$page = get_page(1, 'page_title');
echo $page;
I skipped the foreach as you said that all id's are unique so you should only ever have 1 result
Also it may not be a bad idea to add some error checking to make sure you do get back what you expect from the query and to make sure it is not empty.
Edit: Sorry if the syntax is a little off, dont have anything to test the code against quickly.

Multi dimensional array

Have just come across a problem where I believe this is the solution.
At the moment I have the following code:
function siteUsers()
{
global $database;
$q = "SELECT username, id FROM ".TBL_USERS."";
return mysql_query($q, $this->connection);
}
function generateUserArray()
{
$u = array();
$i = array();
$result = $this->siteUsers();
while( $row=mysql_fetch_assoc($result))
{
$u[] = $row['username'];
$i[] = $row['id'];
}
return $u, $i;
}
As you can see, when I then go onto use foreach, the u and i get split apart.
Is there anyway that I could keep them together?
foreach ($u as $username) {
echo"<option value='$i'>$username</option>";
}
What I need it the option value to be the id and the visual value to be the username.
Is this possible?
Thanks
Use an associative array linking the ID to the username. I'm assuming here the IDs are unique.
$users = array();
while( $row=mysql_fetch_assoc($result))
{
$users[$row['id']] = $row['username'];
}
return $users;
Then:
foreach ($users as $id => $username)
{
echo "<option value='$id'>$username</option>";
}
foreach($u as $idx => $username)
{
echo"<option value='".$i[$idx]."'>$username</option>";
}
assuming equal length and that php function can return two values :\

Categories