Serialize BEFORE the mysql_fetch_array? - php

I'm trying to use memcache but I'm stuck on a small part. I've got a function that gives in result an array of several things (most of them being strings), and one of them is the result of the mysql_query() function.
Here is how I am trying to unserialize:
$posts_count = my query;
/* MEMCACHE KEY GEN*/
$memcache_key = md5($posts);
$pagination = memcache_get($memcache, $memcache_key);
if($pagination==NULL) {
echo 'NOT CACHED';
$pagination = (the function that will call mysql_query)
//SAVE A SERIALIZED VERSION OF THE ARRAY
$memcache->set($memcache_key, serialize($pagination), 0, 3600);
}
else {
$pagination = unserialize($pagination);
}
//THIS IS ONLY THE RESULT OF mysql_query!!!
$posts = $pagination[result];
while($var = mysql_fetch_array($posts)) { ... stuffs here }
Any idea on how to "save" this result of mysql_query before the mysql_fetch_array? Or any idea how to use memcache to cache the whole while loop?

How about something like this:
$posts_count = "my query";
/* MEMCACHE KEY GEN*/
$memcache_key = md5($posts);
$pagination = memcache_get($memcache, $memcache_key);
if ($pagination == NULL) {
echo 'NOT CACHED';
$pagination = function_that_will_call_mysql_query();
// Create an array of all the results
$data = array();
while ($row = mysql_fetch_assoc($pagination['result'])) {
$data[] = $row;
}
$pagination['result'] = $data;
//SAVE A SERIALIZED VERSION OF THE ARRAY
$memcache->set($memcache_key, serialize($pagination), 0, 3600);
} else {
$data = unserialize($pagination);
}
// THIS IS ONLY THE RESULT OF mysql_query!!! (but now it's an array)
$posts = $pagination['result'];
while ($var = array_shift($posts)) {
// ... do stuff here
}

Related

SQL array display in rows without SQL query

I am trying to test a few scripts that I would normally get from an SQL database but for testing offline I am just creating an array.
Here is what I have right now;
$result = array
(
array("name"=>"Toby", "q1"=>"1"),
array("name"=>"Phelps", "q1"=>"1"),
array("name"=>"Davies", "q1"=>"1"),
array("name"=>"Keith", "q1"=>"1"),
);
$resultnum = count($result);
echo "<b>Question 1</b> <br/><br/>";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$name = $row['name'];
$answer = $row['q1'];
$q1answer = 1;
if($answer == $q1answer) {
echo $name . " got this right! <br/>";
} else {
echo $name . " got this wrong! <br/>";
}
}
}
How can I get this to work the same as though it was getting the array from an SQL query instead of just my array, for some reason I can't find a way to get this to run.
You can wrap the array in an anonymous class. Single uses like this are a main reason they exist.
$result = new class {
private $data = array
(
array("name"=>"Toby", "q1"=>"1"),
array("name"=>"Phelps", "q1"=>"1"),
array("name"=>"Davies", "q1"=>"1"),
array("name"=>"Keith", "q1"=>"1"),
);
private $data_index = 0;
public $num_rows;
public function __construct() {
$this->num_rows = count($this->data);
}
public function fetch_assoc() {
if (isset($this->data[$this->data_index])) {
$index = $this->data_index++;
return $this->data[$index];
}
}
};
Similar to the earlier answer, I propose a class. Here I would actually name the class, and pass the data to the constructor. The iteration over the array can be done with the current and next methods:
class ResultSet {
private $array = [];
public $num_rows = 0;
public function __construct($data) {
$this->array = $data;
$this->num_rows = count($this->array);
}
public function fetch_assoc() {
$val = current($this->array);
next($this->array);
return $val;
}
}
Until there it would be fixed. You would play with the data in the following:
$result = new ResultSet([
["name"=>"Toby", "q1"=>"1"],
["name"=>"Phelps", "q1"=>"1"],
["name"=>"Davies", "q1"=>"1"],
["name"=>"Keith", "q1"=>"1"],
]);
I did not implement support for count($result) as I don't think that is supported on real mysqli result sets either. You get the count via ->num_rows (like you also do).

PHP String in Array returns only first charachter

I have a php function to display a list of revslider's sliders (wp plugin), the string returns only the first letter of the sliders' names
here is my code :
function jobboard_revslider(){
if (class_exists('RevSlider')) {
$theslider = new RevSlider();
$arrSliders = $theslider->getArrSliders();
$arrA = array();
$arrT = array();
foreach($arrSliders as $slider){
$arrA[] = $slider->getAlias();
$arrT[] = $slider->getTitle();
}
if($arrA && $arrT){
$result = array_combine($arrA, $arrT);
}
else
{
$result = false;
}
return $result;
}
}
I tried all I know and other answers around here but no hope.
I would really appreciate a push !
Thanks
Check sizeof ($ array)> 0 do this for both arrays. Also just try to echo what you are getting in getalias and gettitle methods before storing it in array.
function jobboard_revslider(){
if (class_exists('RevSlider')) {
$theslider = new RevSlider();
$arrSliders = $theslider->getArrSliders();
$arrA = array();
$arrT = array();
foreach($arrSliders as $slider){
$arrA[] = substr($slider->getAlias(), 1);
$arrT[] = substr($slider->getTitle(), 1);
}
if($arrA && $arrT){
$result = array_combine($arrA, $arrT);
}
else
{
$result = false;
}
return $result;
}

how to fetch all rows from mysql using mysqli_fetch_assoc and convert to JSON

I have tried to get all the rows from mysql table for that am using mysqli_fetch_assoc. While using this am getting only one row. I need to convert the resulting array into JSON.
$query = "SELECT * FROM db_category WHERE publish='1'";
$result = mysqli_query($c, $query) or die(mysqli_error($c));
$length = mysqli_num_rows($result);
if($length > 0)
{
$var['status'] = 'success';
while($obj = mysqli_fetch_assoc($result))
{
$var = array_merge($var, $obj);
$var1 = json_encode($var);
}
echo '{"slider":['.$var1.']}';
}
else
{
$arr = array('status'=>"notfound");
echo '{"slider":['.json_encode($arr).']}';
}
Now the output for above code is,
{"slider":[{"status":"success","category_id":"12","category_name":"Books","publish":"1"}]}
Required output is,
{"slider":[{"status":"success","category_id":"1","category_name":"Apparel","publish":"1"},{"status":"success","category_id":"2","category_name":"Footwear","publish":"1"},{"status":"success","category_id":"3","category_name":"Furniture","publish":"1"},{"status":"success","category_id":"4","category_name":"Jewellery","publish":"1"}]}
How to solve this issue.
You can do it simply by json_encode() function. And you can also get all data into array, with mysqli_fetch_all() function :
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
$jsonData = json_encode(array('slider'=>$data, 'status' => 'success'));
If you want to put 'status'=>'success' for each row, do it like this (before json_encode)
foreach($data as $key => $dataRow) {
$data[$key]['status'] = 'success';
}

Failing to assign values to array from a loop

I have got this code:
function retrieve_answers($array = array(), $id = null)
{
include(root_path . '\config.php');
if($id == null)
{
$id = $this->question_id;
}
$query = mysqli_query($link, "SELECT * FROM `answers` WHERE `question_id`='$id'");
if(!mysqli_num_rows($query))
{
throw new Exception('Question not found.');
}
/* - Retrieves the answer rows
- Loops through the array
- Indexes the array and assigns the answerID to the index */
else
{
while($result = mysqli_fetch_array($query))
{
for($i=0;$i<mysqli_num_rows($query);$i++)
{
$array[$i] = $result["id"];
}
}
}
}
Which is a part of a class.
What am I trying to do?
I am trying to accept an array as a parameter, and assign values to the array, the values are to be answerIDs which are linked to the question.
The test.php file is here:
<?php
define('root_path', realpath(dirname(__FILE__)));
include(root_path . '\config.php');
require_once(root_path . '\includes\question.class.php');
$q = new Question(3);
$array = array();
$q->retrieve_answers($array);
var_dump($array);
?>
What happens?
When I try to debug by dumping the array, it shows that the array contains nothing:
array(0) { }
I tried to execute the MySQL result through the class to debug, and it does succeed to retrieve the answer IDs, so I'm pretty positive the issue is in the array.
I would happy to get assistance, thanks in advance.
return value in a function like this
function retrieve_answers($array = array(), $id = null)
{
include(root_path . '\config.php');
if($id == null)
{
$id = $this->question_id;
}
$query = mysqli_query($link, "SELECT * FROM `answers` WHERE `question_id`='$id'");
if(!mysqli_num_rows($query))
{
throw new Exception('Question not found.');
}
/* - Retrieves the answer rows
- Loops through the array
- Indexes the array and assigns the answerID to the index */
else
{
$i = 0;
while($result = mysqli_fetch_array($query))
{
$array[$i] = $result["id"];
$i++;
}
return $array;
}
}
and then get it as
$arr = $q->retrieve_answers($array);
var_dump($arr);

Return array of SQL results in php to be converted to JSON

I am trying to take a number of user entries from a SQL database and return it where it will be encoded to JSON and sent back to android.
Currently I am building the part to handle the results from querying the database:
$result = mysql_query("SELECT * FROM users WHERE tower='$tower'") or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
//if just one result return it
if ($resultNo == 1) {
// return result
return mysql_fetch_array($result);
//if more than one loop through
} else {
//add each row to an array
while($row = mysql_fetch_array($result)) {
$resultSet[] = $row;
}
return $resultSet[];
} else {
return false;
}
}
The code I am returning to is...
$result = $db->searchForPeople($tower);
Can I return either an array or a single result in this way or should I just add the single result to the array and return that?
Thanks for your help
can this way:
$resultSet['row'] = $row;
return json_encode($resultSet);
or for example:
function TEST()
{
$array=array();$i=0;
while($result=mysql_fetch_row(QUERY))
{
foreach ($result as $key=>$value){
if(!isset($array[$i])) $array[$i] = array();
$array[$i][$key] = $value;
}
$i++;
}
return $array;
}

Categories