Custom buffering of php mysql results - strange issue - php

I discovered something very strange with my PHP code and mysqli functions. When I have my code in the format below:
function mainline(){
$q=mysqli_query($this->conn,"select * from table",MYSQLI_USE_RESULT);
$dataset=parse($q);
}
function parse($q){
if (!$q){return NULL;}
while($res=mysqli_fetch_array($q)){$r[]=$res;}
mysqli_free_result($q);$q=NULL;$res=NULL;return $r;
}
I'm able to retrieve data and process it. In the above example, data is returned to $dataset and each element is retrieved in the form of $dataset[row number][field name].
Now when I change my code so its like this:
function mainline(){
$q=mysqli_query($this->conn,"select * from table",MYSQLI_USE_RESULT);
$dataset=parse($q);
}
function parse($q){
if (!$q){return NULL;}
while($r[]=mysqli_fetch_array($q)); // I made change here
mysqli_free_result($q);$q=NULL;return $r;
}
The data returned is always nothing even though the select statement is exactly the same and always returns rows. During both tests, nothing has modified the data in the database.
My question then is why does while($res=mysqli_fetch_array($q)){$r[]=$res;} retrieve correct results and while($r[]=mysqli_fetch_array($q)); does not?
With the second while loop, I won't have to allocate an extra variable and I'm trying to cut down on the use of system memory so that I can run more apache processes on my system instead of waste memory unnecessarily on PHP.
Any ideas why while($r[]=mysqli_fetch_array($q)); wont work? or any ideas how I can make it work without using an extra variable? or am I stuck?

if you want to store all result in array than why not use
mysqli_fetch_all($q)
and store result in whatever you want. Though if you want to have quick access I
think caching sounds more appropriate.
mysqli_fetch_all — Fetches all result rows as an associative array, a numeric array, or both

Related

I need to add fields to a JSON string in PHP, but I'm having problems

So... I need to save a large-ish amount of data from a platform with an excruciatingly limited amount of memory.
Because of this, I'm basically storing the data on my webserver, using a php script to just write JSON to a flat file, because I'm lazy af.
I could go to the trouble of having it store the data in my mysql server, but frankly the flat file thing should have been trivial, but I've run up against a problem. There are several quick and dirty workarounds that would fix it, but I've been trying to fix it the "right" way (I know, I know, the right way would be to just store the data in mysql, but I actually need to be able to take the json file this produces and send it back to the platform that needs the data (In a ridiculously roundabout fashion), so it made sense to just have the php save it as a flat file in the first place. And It's already working, aside from this one issue, so I hate to reimpliment.
See... Because of the low memory on the platform I'm sending the json to my server from... I'm sending things one field at a time. Each call to the php script is only setting ONE field.
So basically what I'm doing is loading the file from disk if it exists, and running it through json_decode to get my storage object, and then the php file gets a key argument and a value argument, and if the key is something like "object1,object2", it explodes that, gets the length of the resulting array, and then stores the value in $data->$key[0]->$key[1].
Then it's saved back to disk with fwrite($file, json_encode($data));
This is all working perfectly. Except when $value is a simple string. If it's an array, it works perfectly. If it's a number, it works fine. If it's a string, I get null from json_decode. I have tried every way I can think of to force quotes on to the ends of the $value variable in the hopes of getting json_decode to recognize it. Nothing works.
I've tried setting $data->$key[0]->$key[1] = $value in cases where value is a string, and not an array or number. No dice, php just complains that I'm trying to set an object that doesn't exist. It's fine if I'm using the output of json_decode to set the field, but it simply will not accept a string on its own.
So I have no idea.
Does anyone know how I can either get json_decode to not choke on a string that's just a string, or add a new field to an existing php object without using the output of json_decode?
I'm sure there's something obvious I'm missing. It should be clear I'm no php guru. I've never really used arrays and objects in php, so their vagaries are not something I'm familiar with.
Solutions I'm already aware of, but would prefer to avoid, are: I could have the platform that's sending the post requests wrap single, non-numeric values with square braces, creating a single item array, but this shouldn't be necessary, as far as I'm aware, so doing this bothers me (And ends up costing me something like half a kilobyte of storage that shouldn't need to be used).
I could also change some of my json from objects to arrays in order to get php to let me add items more readily, but it seems like there should be a solution that doesn't require that, so I'd really prefer not to...
I skim through your post.
And I know this works for StdClass :
$yourClass->newField = $string;
Is this what you wanted ?
OK so... ultimately, as succinctly as possible, the problem was this:
Assuming we have this JSON in $data:
{
"key1":
{
"key2":["somedata","someotherdata"]
}
}
And we want it to be:
{
"key1":
{
"key2":["somedata","someotherdata"],
"key3":"key3data"
}
}
The php script has received "key=key1,key3&value=key3data" as its post data, and is initialized thusly:
$key = $_POST["key"];
$key = explode($key,",");
$value = $_POST["value"];
...which provides us with an array ($key) representing the nested json key we want to set as a field, and a variable ($value) holding the value we want to set it to.
Approach #1:
$data->$key[0]->$key[1] = json_decode($value);
...fails. It creates this JSON when we re-encode $data:
{
"key1":
{
"key2":["somedata","someotherdata"],
"key3":null
}
}
Approach #2:
$data->$key[0]->$key[1] = $value;
...also fails. It fails to insert the field into $data at all.
But then I realized... the problem with #2 is that it won't let me set the nonexistent field, and the problem with approach #1 is that it sets the field wrong.
So all I have to do is brute force it thusly:
$data->$key[0]->$key[1] = json_decode($value);
if (json_decode($value) == NULL)
{
$data->$key[0]->$key[1] = $value;
}
This works! Since Approach #1 has created the field (Albeit with the incorrect value), PHP now allows me to set the value of that field without complaint.
It's a very brute force sort of means of fixing the problem, and I'm sure there are better ones, if I understood PHP objects better. But this works, so at least I have my code working.

PHP SQL result as whole "object"

I am working on project, which will have limited PHP processes and possibly, many people will use the page. So I am trying to optimize it so the most (but secure) things will be handled clientside.
$result = mysqli_query($db, "SELECT * FROM userdata");
/*return $result; */
while ($row = mysql_fetch_array($result)) {
//do sth, e.g. get row to array
}
/*return $array;*/
My question is simple in this case.
Looping through each line takes time and will block the php process for quite a time.
So, is here some solution, taht you will simply send SQL requests, from DB server you will get response in shape of "some bunch of data", that I will be able to pass directly to jquery, where I can handle/sort/edit/make viewable the result using client resoruces and not server resources?
(so far, making sql request and passing $result to jquery variable seems not returning anything, the jquery variable is empty)
Thanks in advance
First of all, it looks like you are mixing mysql with mysqli.
mysqli method:
mysqli_query($db, "SELECT * FROM userdata");
mysql method:
mysql_fetch_array($result)
You SHOULD NOT do this. mysql method is deprecated, and both method are different api entirely, they are not meant to work together, eventhought its work, it is plain wrong to do so.
As for you question, in order to pass the fetched db data result to jQuery or Javascript for client side processing, you can convert the result array to JSON strings.
Do like this:
$row = mysqli_fetch_array($result);
echo json_encode($row);
Then using jquery, make ajax call to the php script. and parse the json data.
I think you're asking for this function :
http://www.w3schools.com/php/func_mysqli_fetch_all.asp
which will retrieve ALL the rows into a single nested associative array. You can then encode this array using JSON_encode() to process using client-side javascript.

While loop is not working properly

I am having a while loop in my function for getting the values 1 by 1 but i am getting the only 1 value
while($row= mysqli_fetch_array($this->result))
{
$image=$this->getEventDetails($row['Album_top'],'Event_image');
$alert.="<div class=facBox>
<a href='gallery.php?id=$row[Id]' style=margin-top:0px;>
<img src='admin/customer/eventgallery/$image' alt=''>
</a>
<div class=clear></div>
<a href='gallery.php?id=$row[Id]' style=margin-top:0px;>$row[Album_title]</a>
</div>";
}
I am getting the image name from another function that is
function getEventDetails($id,$fieldname)
{
$get="Select * from sarnaevent where Id='$id'";
$this->result=mysqli_query($this->con,$get);
$row=mysqli_fetch_array($this->result);
return $row[$fieldname];
}
Now i am getting the only value from the loop my $alert is having only one facbox. if i remove this line
$this->getEventDetails($row['Album_top'],'Event_image');
It works fine but i want this line to get the image name.
Inside getEventDetails(), you assign $this->result, overwriting the previous contents of $this->result. Since that occurs inside the while loop where the previous result is being used, the loop exits because there are no further results to retrieve from the inner fetch.
User a different temporary result set inside teh getEventDetails() method.
function getEventDetails($id,$fieldname)
{
$get="Select * from sarnaevent where Id='$id'";
// Different variable name...
$temporary_result = mysqli_query($this->con,$get);
$row=mysqli_fetch_array($temporary_result);
return $row[$fieldname];
}
In general, I would question the need to be storing a transient result resource into the object's $this->result for most purposes. In any case where you're using that inside a method, you are probably better off using a variable scoped only to the method, which lives only for the lifetime that result set is being used.
Please use caution when sending $id directly into the query. Although I suspect it is known to be an integer variable, and therefore it won't break the SQL, it's a good idea to get into the habit of using prepare()/execute() to prevent SQL injection.
One final point of caution: When placing the string variable into your HTML markup, be sure to use htmlspecialchars() to escape it against malforming the HTML. (If the Id is known to be an integer, it isn't necessary there)
"...<a href='gallery.php?id=$row[Id]' style=margin-top:0px;>" . htmlspecialchars($row['Album_title']) . "</a>..."
Instead of using mysqli_fetch_array() try using mysqli_fetch_assoc (see: http://php.net/manual/en/mysqli-result.fetch-assoc.php); the returned array will be associative (key-value pairs) where the keys are the column names.
You're blowing out your original query.
First, you do a query, and assign its result to $this->result. You then iterate across those results. For the first row, you immediately make a new query, overwrite $this->result with the new results, and then try to continue... but you've just replaced the rest of your results with the single result from the event details query, so mysqli_fetch_array doesn't find any more results.
Solution: use a separate variable for that result. A local one should be fine, since you don't use it outside that function. You may also need to use a separate connection; I'm not sure of that. Try it with just changing $this->result in getEventDetails() to use something like $eventResult instead.

How to make a function to return the results of a prepared statement?

I am currently using this function to get categories data from mysql database.
function GetCategories()
{
$AryCategories = '';
require("cnt.php"); // opening a connection.
if($stmnt_get_categories = mysqli_prepare($con,'SELECT type_id,type_name FROM `tblpolltypes` order by type_name;'))
{
mysqli_stmt_execute($stmnt_get_categories);
mysqli_stmt_bind_result($stmnt_get_categories,$cat_id,$cat_name);
while(mysqli_stmt_fetch($stmnt_get_categories))
{
$AryCategories[$cat_id]=$cat_name;
}
mysqli_stmt_close($stmnt_get_categories);
}
mysqli_close($con);
return $AryCategories;
}
It is working fine but using this code means I am looping the returned array again which means processing the same data twice:
the first: when I'm looping the statement results to store it in the array inside the function.
the second: when i'm looping the returned array to "echo" the data.
is there a better way to write this like returning the whole statement? or fetching the data directly in a multidimensional array without having to loop it?
is there a better way to write this like returning the whole statement?
No.
There is nothing wrong with it, as long as you return only sane amount of data for the average web page.

conditional in_array trouble with PHP mySQL

I have firePHP so i know exactly what the variables are, but I can't figure out why this code doesn't change it.
I receive from a mySQL call $query (which if returned produces [{"type":"2"}])
I have 4 potential types, and things can be multiple types (i.e. [{"type":"1"},{"type":"2"}])
Now I want to read this data and run various other functions based on the type it has, that is: if it's only type 2, call function TWO, if it's type 1 and 2 call function ONE and function TWO. I thought this would be easiest if i moved all the data into another array.
Here is the code I currently have:
$result = array('message'=>false, 'money'=>false, 'glasses'=>false, 'exclamation'=>false);
if (in_array('1',$query)) {$result['message'] = true;}
if (in_array('2',$query)) {$result['money'] = true;}
if (in_array('3',$query)) {$result['glasses']=true;}
if (in_array('4',$query)) {$result['exclamation']=true;}
echo json_encode($result);
This however does not update the $result array (as I can tell all of the values of $message are false in firePHP.... Thus I assume something is wrong with my if statements, but what?
I´m not sure about the value of $query, but if it is something like:
array [0 => '{"type":"2"}']
You would have to use:
in_array('{"type":"2"}',$query)
as that is the value of your variable.
Is it because the results returned in $query are arrays of arrays, and thus in_array is only searching at the top level and not sub-levels? It seems like what you want is to recursively search $query.

Categories