MySQL to JSON via PHP - php

Let me preface this with I know this question has been asked plenty of times on here (ie here among other pages) and I've trawled through each of the answers and tried the solutions but keep getting an empty json array.
I've got a mysql query as per below:
$myQuery = $wpdb->get_results('SELECT player_name, player_team,
SUM(ruckContests) AS contests FROM afl_master
WHERE player_team = "COLL" AND year = 2019 AND ruckContests > 0
GROUP BY player_id ORDER BY contests DESC LIMIT 2');
The output to this query is as follows:
Array ( [0] => stdClass Object ( [player_name] => Brodie Grundy [player_team] => COLL [contests] => 661 ) [1] => stdClass Object ( [player_name] => Mason Cox [player_team] => COLL [contests] => 51 ) )
What I want to do is convert this to the following json object in php:
{
player_name: "Brodie Grundy",
player_team: "COLL",
contests: 661
},
{
player_name: "Mason Cox",
player_team: "COLL",
contests: 51
}
I've tried mysql_fetch_array() as well as fetch_assoc() using the method here but to no avail. I'd appreciate any help available.
This simple solution recommended in the comments worked:
json_encode($myQuery)

$JsonData=array();
foreach($myQuery as $val){
$JsonData[]='
{
"player_name": "'.$val->player_name.'",
"player_team": "'.$val->player_team.'",
"contests": $val->contests
}
';
}
$expectedJson=implode(',',$JsonData);

Just cast your result to array with fetch_array() or (array) $myQuery then:
json_encode($myQuery);
json_last_error(); // to see the error

You can do it in single SQL Statement (I have just formatted it in multiple lines for better understanding). The inner Select statement uses your query as a sub-query, while using JSON_OBJECT to generate JSON object of each row, finally using GROUP_CONCAT to combine each row with a comma, and then add the "[" and "]" to the final result for creating a perfect JSON array. (Just another way, apart from the json_encode($myQuery), the simpler version :) ).
SELECT CONCAT('[',
GROUP_CONCAT(
JSON_OBJECT(
'player_name', player_name,
'player_team' , player_team,
'contests', contests)
) , ']') as json
FROM (
SELECT player_name, player_team, SUM(ruckContests) as contests
FROM afl_master
WHERE player_team = "COLL" AND year = 1995 AND ruckContests > 0
GROUP BY player_name, player_team
ORDER BY SUM(ruckContests) DESC
LIMIT 2
) AS TT

Related

PHP SQL - Search for match with same players

Good mornin'.
I've been tryin to make "something" that will compare matchup percentage but i'm stuck'd at searching for matches with 2 same players.
I've found something about AND OR parenthesis so here is my sql query
$ccc = "SELECT * FROM zapasy WHERE (playerName01 = '".$player1."' OR playerName01 ='".$player2."') AND (playerName02 = '".$player2."' OR playerName02='".$player1."')";
$result3 = $db->query($ccc);
$ids = array();
while ($row55 = $result3->fetch_assoc())
{
$ids[] = $row55['winner'];
}
But , the problem is whenever i try to get data , it gives me more indexes than actualy expected.
This is the result of printing array values after fetching.
Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 )
As expected is only 2 3 4 as u can see in the DB sample here.
db sample
Anyone suggestions on what i'm doing wrong?
A simple way to write this in MySQL uses tuples:
where (?, ?) in ( (playername01, playername02), (playername02, playername01) )
The ? are for parameters. That should be the way that you pass values into queries.
You are doing wrong while using AND OR in where clause
$ccc = "SELECT * FROM zapasy WHERE (playerName01 = '".$player1."' AND playerName02 ='".$player2."') OR (playerName01 = '".$player2."' AND playerName02='".$player1."')";
Try this #Patrik Dano

Using pure MySQL query instead of php loop and statements to get same result

I would like to turn this code into a more pure MySQL. This code fetches a row according to each word in $words and it creates $translated word array.
$words = array("word1","word2","word3"...);
$translated = array();
foreach($words as $word){
$query = "
select * from (
select text1,text2,text3
from table1
union
select text1,text2,text3
from table2
union
select text1,text2,text3
from table3
) as u
where u.text1 = ? or u.text2 = ?";
$prepare = $database -> prepare($query);
$prepare -> execute(array($word,$word));
$fetch = $prepare -> fetch();
if($fetch["text3"]){ $push = $fetch["text3"]; }
else if($fetch["text1"]){ $push = $fetch["text1"]; }
else{ $push = $word; }
array_push($translated, $push);
}
This PHP solution seems really inefficient to me. I would like to find a pure MySQL solution. So far I've been working on this MySQL but it lacks the ending logic.
$query="
select
if(text2='word1',text3,0) as W1,
+ if(text2='word2',text3,0) as W2,
+ if(text2='word3',text3,0) as W3,
...
from (
select text1,text2,text3
from table1
union
select text1,text2,text3
from table2
union
select text1,text2,text3
from table3
) as u where
u.text1 in('word1','word2','word3'...) or
u.text3 in('word1','word2','word3'...)
";
This give out something like:
Array (
[0] => Array ( [word1] => 0 [word2] => word22 [word3] => 0 [word4] => 0 )
[1] => Array ( [word1] => word23 [word2] => 0 [word3] => 0 [word4] => 0 )
[2] => Array ( [word1] => 0 [word2] => 0 [word3] => word24 [word4] => 0 ) )
I can column search for non-zero entry to find the translation. BUT, I am not sure how to add logic to the MySQL to select default text1 if text3 is missing.
if($fetch["text3"]){ $push = $fetch["text3"]; }
else if($fetch["text1"]){ $push = $fetch["text1"]; }
else{ $push = $word; }
array_push($translated, $push);
You could quite easily work at least some of your default logic into your current 'more pure SQL' example (which ultimately requires quite a bit of looping in PHP, I assume). You do not specify what text3 is when it is 'missing', but the following would work for either null or an empty string
if(text2='word1', IF(CHAR_LENGTH(text3), text3, text1), 0) as W1
If 'missing' reliably means null for text1 and text3, your entire default value logic from PHP could be expressed as
if(text2='word1', COALESCE(text3, text1, 'word1'), 0) as W1
I can't say I'm a big fan of this solution, but unfortunately I have not come up with an SQL only silver bullet for you, either. I'm also not an advocate of optimization for the sake of optimization. You have not stated how large the $words array might get, but if this part of your software is not materially impacting performance for you, time spent 'fixing' it would probably be better spent elsewhere.
The most glaring inefficiency in your original approach could be somewhat ameliorated by moving the SQL statement preparation out of the foreach loop; it does not need to be done repeatedly.
You could also work the default value logic into the SQL of your original approach (though I can't say if it would actually improve performance) by adapting the CHAR_LENGTH or COALESCE suggestions from above. Something along the lines of
SELECT COALESCE(text3, text1, ?) AS translated FROM (...) as u...

create multi-dimensional array in php

I am having trouble trying to figure out how to populate a multi-dimensional array. Let's say I have a table of transactions with various billing dates. First I have an array that retrieves the following 'billed' dates:
Array
(
[0] => Array
(
[BILLED] => 2011-11-18 00:00:00
)
[1] => Array
(
[BILLED] => 2011-11-22 00:00:00
)
)
I also have the following query which is currently hard-coded to one of the two 'billed' dates shown above:
$qryOrders = $this->db->query("
SELECT tblOrders.*
FROM tblOrders
WHERE tbltc.BILLED = '2011-11-22'");
$data['Orders'] = $qryOrders->result_array();
I know that I can very easily determine the count of array items by using count($Orders); but how can I instead pass through each of the 'billed' dates of 2011-11-18 and 2011-11-22 to that I can determine the overall count, for both of the specified dates?
I hope I've explained it clearly enough. I am thinking that I probably need some kind of foreach loop and each time through the loop I could pass in the billed date, and keep track of a running total each time through the loop.
Any ideas would be greatly appreciated. Thanks,
// this is getting all results for a record
$sql =
<<<sql
SELECT tblOrders.*
FROM tblOrders
WHERE tbltc.BILLED between '{$arr[0]}' and '{$arr[1]}'
sql;
// this is to get total count of matched record
// $sql = 'select count(*) from ..';
if you are using CI, you can easily using bind
example:-
$sql = 'SELECT tblOrders.* FROM tblOrders WHERE tbltc.BILLED between ? AND ?';
$this->db->query($sql, array($arr[0], $arr[1]));

The best way to select rows from several tables?

I am creating a php app and am now creating the DB interface code. In my APP their are three tables, user, network, user_network. They have the following columsn:
user<-------------------->user_network<-------------------->network
user_ID un_ID network_ID
user_Name un_Member network_Name
un_Network network_Description
I have created the following query which querys the user_network table and returns the ID's of all networks which the user is a member of:
$STH = $DBH->query("SELECT * FROM user_network WHERE nm_Member ='$userID'");
I then pull the network_ID's from this array using the following code:
$DB_NetworkID = array();
foreach($STH as $row)
{
$DB_NetworkID[$counter] = $row['nm_networkID'];
$counter++;
}
print_r($DB_NetworkID);
The array now holds of all the network IDs that the user is a member of, like so
Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 7 ) //network IDs = 1, 3, 5, 7
I would now like to pull rows from the networks tables, how do i go about about SELECTing rows from the networks database WHERE the ID is contained in the array?
Thanks for any help.
You should use a JOIN instead and make it a single query:
SELECT
*
FROM
user
INNER JOIN
user_network
ON
user.user_ID = user_network.un_ID
INNER JOIN
network
ON
user_network.un_Network = network.network_ID
WHERE
user_ID = '$userID'
That query will give you all networks that a user is member of.
If your problem is the comparison against an array, then an easy workaround is using FIND_IN_SET() like this:
$list = implode(",", $DB_NetworkID); // turns it into "1,3,5,7"
... "SELECT * FROM foo WHERE FIND_IN_SET(network_ID, '$list')";
For better performance you should construct an .. IN (?,?,..) clause however.
Of course using JOIN as "halfdan" said, is the best way.
But I gonna answer your question:
If your array is like this:
$un = Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 7 ) //network IDs = 1, 3, 5, 7
You can use a Foreach like this:
Foreach($un as $key => $value) {
and your query will be like this:
SELECT * FROM network WHERE network_ID ='$value'

How to get the result of a query with values in a array?

This is my function where i fetch my results from database
function Prof_Viewer($MemberId)
{
$query = $this->db->query("SELECT distinct(t1.dProfileId) as prof
FROM tbl_profile_viewer as t1
JOIN tbl_login as t2
WHERE t1.dProfileViwerId='$MemberId'");
if($query->num_rows > 0)
{
foreach($query->result() as $row)
{
echo $row->prof;//i am receiving many values here
$query1 = $this->db->query("SELECT distinct(t3.dUser_name),t2.dPath,t3.dCreatedDate
FROM tbl_login as t3
JOIN tbl_profile_viewer as t1,
tbl_member_details as t2
WHERE t3.dMember_Id = '$row->prof'
AND t2.dMember_Id ='$row->prof'");
}
return $query1->result_array();
}
}
As commented above i receive many values while echo the variable $row->prof;
say i have values such as 1 2 and 3.......
Even if i have these three values my 'query1' takes only the last value .so i have only one result i want the query to be executed for 1 and 2 also
how to Achieve that
You can just use PHP's explode() to convert your string into an array. For example:
<?php
$str = 'one|two|three|four';
// positive limit
print_r(explode('|', $str));
// gives you an array:
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
)
?>
But I think you would be better off if you learned how to do JOIN's:
http://en.wikipedia.org/wiki/Join_(SQL)
I'm assuming you're using mysqli here.
Result_fetch_array() will do what you want
http://au2.php.net/manual/en/mysqli-result.fetch-array.php

Categories