how to convert an cakephp mysql result into a simple array - mysql

App::import('model','User');
$user_model = new User();
$xxx = $user_model->find("all", array("fields"=>array("User.yyy")));
$zzz = $user_model->find("count", array("fields" => "User.yyy"));
$arr = array();
for($i=0; $i<=$zzz; $i++){
$rs = $xxx["i"]["User"]["yyy"];
array_push($arr , $rs);
}
print_r($arr);
I am using the above cakephp code to get $xxx as a mysql result set.
I need to store all the values corresponding to "yyy" field in the mysql table into an arrray.
I tried printing the result set and got output like this:-
print_r($zzz)= 1646 // prints the total number of results
print_r($xxx[0]["User"]["yyy"]) = abcde //the first element of the result set
After I run the code above, It just prints an empty array.
Can someone help me out here??

The problem is here:
$xxx["i"]["User"]["yyy"]
It should be:
$xxx[$i]["User"]["yyy"]
Assuming the code is located in a controller, I would write it like this:
$this->loadModel('User');
$arr = $this->User->find("list", array("fields"=>array("User.yyy")));
find("list") should return an array indexed by id
If you want to remove the ids, you can do this:
$arr = array_values($arr)

Related

How to order sql results by number of occurences of substr in string [duplicate]

I am wanting to count all occurrences of the # symbol in a field and originally i thought LIKE '%#%' would be the way to go, but if the character appears in the field more than once it only counts it as one.
What other method are there that i could use that would count every occurrence?
Thanks.
EDIT
For anyone needing it, this is what i ended up using that works.
$count = 0;
$sql = mysql_query("SELECT LENGTH(field_name) - LENGTH(REPLACE(field_name,'#','')) AS 'occurs' FROM table_name WHERE field_name LIKE '%#%'");
while ($data = mysql_fetch_assoc($sql)) {
$count += $data['occurs'];
}
echo $count;
select length('aa:bb:cc:dd')-length(replace('aa:bb:cc:dd',':',''));
source: http://lists.mysql.com/mysql/215049
You could make this even simpler by using the ``substr_count function in php. see below.
$message = $row['themessage'];
echo substr_count($message, '#');
what this will return is the number of times # has occurred in your "themessage" field in your database.

How can I grab multiple records from a MySQL query in Perl using array pointers?

I can do this all as one function, but in trying to port it over to my packages of functions (library) I am missing something.
Here's what I want to do from my main Perl script
my #rows;
$result = Funx::dbcdata($myConnection,
"SELECT * FROM Inv where name like \"%DOG%\";", \#rows);
Then in my library package I am attempting this
sub dbcdata
{
my ($connection, $command, $array) = #_;
my $query = $connection->prepare($command);
my $result = $query->execute();
my $i =0;
while(my $row = $query->fetchrow_arrayref() )
{
#{$array}[$i] = $row;
$i++;
}
$query->finish;
return $result;
}
I was hoping to get back pointers or references to each row (which was 4in this case) but am not. Every element in #rows is the same:
ARRAY(0x5577a0f77ec0) ARRAY(0x5577a0f77ec0) ARRAY(0x5577a0f77ec0)
ARRAY(0x5577a0f77ec0)
Nor do I know how to turn each one into the original separate row. Any help would be appreciated, thanks.
From the documentation for fetchrow_arrayref:
Note that the same array reference is returned for each fetch, so don't store the reference and then use it after a later fetch. Also, the elements of the array are also reused for each row, so take care if you want to take a reference to an element.
Sounds like you want fetchall_arrayref:
The fetchall_arrayref method can be used to fetch all the data to be returned from a prepared and executed statement handle. It returns a reference to an array that contains one reference per row.
After executing the statement, you can do something like
#{$array} = $query->fetchall_arrayref->#*;
instead of that ugly loop.
But selectall_array might be even better. Your whole function can be replaced by a call to it:
my #rows =
$myConnection->selectall_array(q/SELECT * FROM Inv WHERE name LIKE '%DOG%'/);

Keep receiving error on SELECT SUM Query

Okay, so I found the mysqli format:
$resultDN7 = $db->query("SELECT SUM(`donation_resources`) as `totalDN7` FROM ztn_com_donations WHERE donation_playerid='$player_id' AND donation_corpsid='$player_corpsid' ");
$rowDN7 = $resultDN7->fetch_assoc();
echo $rowDN7['totalDN7'];
$pladon = ( $rowDN7['totalDN7'] );
Okay if you notice that last line, I must get the result changed into a variable. I could not find documentation on that, just an example as below:
if ($rowDN7)
{ $pladon = $row[0]; }
Is this correct?
mysql_result() expects parameter 2 to be int and you are giving it string
The documentation says
The row number from the result that's being retrieved. Row numbers start at 0.
Since in your case DISTINCT SUM(donation_resources) it will only return 1 row
It should be like
echo mysql_result($resultDN7, 0);
Where $resultDN7 is the resource and 0 is the row

JSON giving unwanted row index number - Active Record - Codeigniter

I don't know why when I echo json_encode a query result set I get the number of the result row before each object. I just want to count the number of total rows returns and have them displayed only once in the beginning of the JSON string and then just the rows returns afterwards. I.e. using the following code:
//...active record query
$result = $this->db->get();
$data = array();
$count = 1;
foreach($result->result() as $row)
{
$data['count'] = $count;
$entry = array();
$entry['firstname'] = $row->first_name;
$entry['lastname'] = $row->last_name;
$entry['jobtitle'] = $row->title;
$entry['dept'] = $row->dept_name;
$entry['deptid'] = $row->dept_no;
if($row->emp_no == null)
{
$entry['ismanager'] = 0;
}
else
{
$entry['ismanager'] = 1;
}
$data[] = $entry;
$count++;
}
return $data;
and then json_encode it in the controller, I get:
{"count":35,"0":{"firstname":"Georgi","lastname":"Facello","jobtitle":"Senior Engineer","dept":"Development","deptid":"d005","ismanager":0},"1":{"firstname":"Kirk","lastname":"Facello","jobtitle":"Senior Engineer","dept":"Development","deptid":"d005","ismanager":0},....rest of the query results
What I don't want is the "0" and "1" etc, before the row results. I already have the total count of the returned results so I don't need the individual row numbers.
If someone could kindly help me out I would appreciate it, thanks.
If you try to serialize an array as JSON, it would become something like this:
[elem1, elem2, elem3, ...]
But if that "array" have other fields then it will be serialized as an object:
{"field":value, "0":elem1, "1":elem2, "2":elem3, ...}
Since there's no way to serialize field using the array syntax, and json_encode can not simply discard it, then it uses the object syntax. As stated in the docs:
Note:
When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.
A possible workaround for this would be separating the count from the list of elements:
$data = array();
$list = array();
$data['list'] = list;
$count = 1;
foreach($result->result() as $row)
{
$data['count'] = $count;
$entry = array();
...
$list[] = $entry;
$count++;
}
That would serialize to something like:
{"count":35,"list":[{"firstname":"Georgi","lastname":"Facello","jobtitle":"Senior Engineer","dept":"Development","deptid":"d005","ismanager":0},{"firstname":"Kirk","lastname":"Facello","jobtitle":"Senior Engineer","dept":"Development","deptid":"d005","ismanager":0},....rest of the query results]}
It looks like you might be using JSON_FORCE_OBJECT on your json_encode which will always make your numerical index show up as a property. You should show your json_encode step in your question.
If you turn option off and go with a default encoding, you will still need to nest your numerically indexed array in its own property or the numerical indexes will show up as properties in order to make valid JSON. For perhaps do something like this when assigning your rows to the object:
$data['records'][] = $entry;

php array_walk_recursive not working on mysql result set array with stripslashes

I have a mysql result array and I'm trying to stripslashes on the array using array_walk. It's not stripping slashes from mysql. It is working on the array I manually added ($dataArr['xxx']) though.
Here is my code:
$sql = ' select * from `ads` where id = 3 ';
$res = mysql_query($sql, $conn) or die(mysql_error());
$row = MYSQL_FETCH_ASSOC($res);
$dataArr = $row;
$dataArr['xxx'] = '<script type=\'text/javascript\'><!--//<![CDATA[
var m3_u = (location.protocol==\'https:\'?\'https://ads.test.com/www/delivery/ajs.php\':\'http://ads.test.com/www/delivery/ajs.php\');
var m3_r = Math.floor(Math.random()*99999999999);
if (!document.MAX_used) document.MAX_used = \',\' etc.... etc....;
';
array_walk_recursive($dataArr, 'stripslashes');
print '<pre>'; print_r($dataArr); print '</pre>';
Some recommendations:
1) Remove the leading and ending spaces in your query.
2) mysql_fetch_assoc should be in lowercase.
3) Bare in mind that mysql_fetch_assoc only returns one row at a time. You need to work with a while loop to fetch all the results. See examples in the documentation.
4) You might prefer to use mysql_fetch_array instead of mysql_fetch_assoc. See here.