pretty sure this is something easy but i cant figure it out, basicly making a easy query like this:
$result = $mysqli->query("SELECT t.name FROM cups_participants cp
LEFT JOIN teams t on cp.team_id = t.team_id
WHERE cp.cup_id = '1'");
the above query should get all the names out of the database, now i want it to be put into array like this:
$competitors = array(
'Paul A.M. Dirac',
'Hans Christian Oersted',
'Murray Gell-Mann',
'Marie Curie',
'Neils Bohr',
'Richard P. Feynman',
'Max Planck');
how do i get the result from my query into a array like the above on?
$competitors = array();
$result = $mysqli->query("SELECT t.name FROM cups_participants cp
LEFT JOIN teams t on cp.team_id = t.team_id
WHERE cp.cup_id = '1'");
if($result->num_rows > 0)
{
while($rs = $result->fetch_assoc())
{
$competitors[]=$rs['name'];
}
}
echo "<pre />";
print_r($competitors);
Related
I am working with a very large table in MySQL containing employee information collected over the last four years. I want to know if someone's job code changed between that time, and if so, push their data into an array for json encoding in php.
An example of the data looks like this:
Year Emp ID Job Code
2015 1234 X908
2014 1234 X908
2013 1234 X908
**2015 5421 Y444**
2014 5421 Z900
2013 5421 Z900
For employee 1234 there has been no job change between 2013-2015; I would however like to catch employee 5421 whose job code changed between 2014 and 2015.
So far, I have written a script in PHP without good results.
$query = mysqli_query("SELECT year, emp_id, job_code from big_table ");
$rows = array();
while ($r = mysql_fetch_assoc($query)) {
if ($r['emp_id'] == $r['emp_id'] and $r['job_code'] != $r['job_code']) {
$rows[] = $r;
}
echo json_encode($rows);
Thank you in advance for your help!
You can get the required data in the SQL query without having to pull all user records into PHP. This will be significantly more efficient than processing the data in PHP.
You can get the job code count for each user:
SELECT emp_id, COUNT(DISTINCT job_code) AS diffjobs FROM big_table GROUP BY emp_id
Then you can conditionally get users with more than 1 distinct job code by wrapping it in a subquery:
SELECT emp_id, diffjobs FROM
(SELECT emp_id, COUNT(DISTINCT job_code) AS diffjobs FROM big_table GROUP BY emp_id) d
WHERE diffjobs > 1
This loop should work:
$rows = array();
$jobChanges = array();
while ($r = mysql_fetch_assoc($query)) {
if (!isset($rows[$r['emp_id']])){
$rows[$r['emp_id']] = $r;
} elseif ($rows[$r['emp_id']]['job_code'] != $r['job_code']) {
// Handle differing job_code...
if (!isset($jobChanges[$r['emp_id'])) {
$jobChanges[$r[emp_id]] = array();
}
// Keep track of all differing job codes per emp_id
// I am not going to go any further than that...
$jobChanges[$r[emp_id]][] = $r;
}
}
You can get the desired employees whose job has changed in between years using GROUP BY and HAVING clause, like this:
$query = mysqli_query($link, "SELECT emp_id from big_table GROUP BY emp_id HAVING COUNT(DISTINCT job_code) > 1");
$rows = array();
while ($r = mysqli_fetch_assoc($query)){
$rows[] = $r;
}
echo json_encode($rows);
Caution: Don't mix mysqli and mysql database extensions in your code.
This can be done with a JOIN query in MySQL, so that you only return the rows that have changed from the previous year -
SELECT
a.year, a.emp_id, a.job_code,
b.year prev_year, b.job_code prev_job_code
FROM big_table a
JOIN big_table b
ON a.emp_id = b.emp_id
AND b.year = a.year-1
WHERE a.job_code != b.job_code
see this SQLFiddle - http://sqlfiddle.com/#!9/95e680/10
so your code could be simplified to -
$query = mysqli_query("SELECT a.year, a.emp_id, a.job_code, b.year prev_year, b.job_code prev_job_code FROM big_table a JOIN big_table b ON a.emp_id = b.emp_id AND b.year = a.year-1 WHERE a.job_code != b.job_code ");
$rows = array();
while ($r = mysqli_fetch_assoc($query)) {
$rows[] = $r;
}
echo json_encode($rows);
note - you had mysqli_query(), but mysql_fetch_assoc(), so I updated to mysqli_fetch_assoc()
If you still wanted to do this in php, you need to save the last row value to a temporary array, and then check if the job_code has changed.
it would look something like this -
$query = mysqli_query("SELECT year, emp_id, job_code from big_table ORDER BY emp_id, year");
$temp = array();
$rows = array();
while ($r = mysqli_fetch_assoc($query)) {
if(!isset($temp[$r['emp_id']]){
$temp[$r['emp_id']] = $r; // add this row to the temp array
}
else {
if ($r['job_code'] != $temp[$r['emp_id']]['job_code']) {
// add the previous values for comparison
$r['prev_year'] = $temp[$r['emp_id']]['year'];
$r['prev_job_code'] = $temp[$r['emp_id']]['job_code'];
// add this row
$rows[] = $r; // add this row
// replace the last temp array with this array
$temp[$r['emp_id']] = $r;
}
}
echo json_encode($rows);
note - I changed the query by adding an ORDER BY -> ORDER BY emp_id, year
So I have this array data which i want to be coded somewhat like [lojas, raparacoes, valor],[nome_1, count_1, val_1],[nome_2, count_2, val_2], etc, etc...
lojas, reparacoes and valor are like headers
nome_* comes from $row['nome']
count_* comes from intval($row['COUNT( DISTINCT id_reparacao )'])
val_* comes from intval($row2['SUM(valor)'])
$data = array(array('Lojas'), array('Reparacoes'), array('Valor'));
$qry=mysql_query ('SELECT COUNT( DISTINCT id_reparacao ) , lojas.nome, lojas.id
FROM reparacoes
INNER JOIN lojas ON lojas.id = id_loja
GROUP BY lojas.id ');
while($row = mysql_fetch_array($qry))
{
$qry2=mysql_query ('SELECT SUM(valor) FROM re_servicos where id_reparacao=(select id_reparacao from reparacoes where id_loja='.$row['id'].' and estado="Fechada")');
while($row2 = mysql_fetch_array($qry2))
{
$data=[$row['nome'],intval($row['COUNT( DISTINCT id_reparacao )']), intval($row2['SUM(valor)'])];
}
}
However, with this code I'm not getting the desired output in the array, I guess the problem is the way i fill it but I don't know how to properly fill it so it gets the output I posted in the first paragraph.
PS: I don't know if it matters but for better understanding, I need this array to build a google bar chart
You can try this code.
$data = array();
$data[] = array('Lojas', 'Reparacoes', 'Valor');
$qry=mysql_query ('SELECT COUNT( DISTINCT id_reparacao ) , lojas.nome, lojas.id
FROM reparacoes
INNER JOIN lojas ON lojas.id = id_loja
GROUP BY lojas.id ');
while($row = mysql_fetch_array($qry))
{
$qry2=mysql_query ('SELECT SUM(valor) FROM re_servicos where id_reparacao=(select id_reparacao from reparacoes where id_loja='.$row['id'].' and estado="Fechada")');
while($row2 = mysql_fetch_array($qry2))
{
$data[]=array($row['nome'],intval($row['COUNT( DISTINCT id_reparacao )']), intval($row2['SUM(valor)']));
}
}
I currently have this query with an array that outputs the variables within using a dynamic input in my form (term), this creates a Dynamic Search with auto complete to fill in all of the details for a product.
$return_arr = array();
$param = $_GET["term"];
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
//$row_array['category_id'] = $row ['category_id'];
$row_array['product_id'] = $row['product_id'];
$row_array['product_names'] = $row['name_en-GB'];
$row_array['jshop_code_prod'] = $row['product_ean'];
$row_array['_ext_price_html'] = number_format($row['product_price'],2);
if (!empty($row['product_thumb_image']) AND isset($row['product_thumb_image'])){
$row_array['image'] = $row['product_thumb_image'];
}else {
$row_array['image'] = 'noimage.gif';
}
array_push( $return_arr, $row_array);
}
mysql_close($conn);
echo json_encode($return_arr);
Unfortunately I also need to get the category_id which is not in the same table, I have tried to modify my query as such, but to no avail:
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param' AND `crd_jshopping_products_to_categories` = `product_id` ");
What step am I missing here ? The product_id's match in both tables?
try this query instead and try to understand what I have written in it:
$fetch = mysql_query("
SELECT
p.*,
c.category_id
FROM
crd_jshopping_products as p
INNER JOIN crd_jshopping_products_to_categories as c
ON p.product_id = c.product_id
WHERE
`p.name_en-GB` REGEXP '^$param'
");
This means:
SELECT:
Give me everything from p and the category_id from c.
FROM:
Do this from rows in the tables crd_jshopping_products (referred to as p) and crd_jshopping_products_to_categories (referred to as c), where the rows match on the count of p.product_id is the same as c.product_id.
WHERE:
Only return the rows where p.name_en-GB REGEXP '^$param'.
I would like to know how I could join these 3 queries together as I'm wanting only one JSON output, I thought INNER JOIN would do this. But don't know how to use this. Can someone guide me onto the right path please?
$json = array();
$following_string = mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="SELECT * FROM streamdata WHERE streamitem_id < '$lastID' AND streamitem_target=".$following_string." OR streamitem_creator=".$following_string." ORDER BY streamitem_id DESC LIMIT 10";
$chant = mysqli_query($mysqli, $call) or die(mysqli_error($mysqli));
$json['streamdata'] = array();
while ($resultArr = mysqli_fetch_assoc($chant)) {
$json['streamitem_id'] = $resultArr['streamitem_id'];
$json['streamitem_content'] = $resultArr['streamitem_content'];
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
$json['streamdata'] = $json;
}
/***** COMMENTS *****/
$check = "SELECT comment_id, comment_datetime, comment_streamitem, comment_poster, comment_content FROM streamdata_comments WHERE comment_poster=".$following_string." ";
$check1 = mysqli_query($mysqli,$check);
$json['streamdata_comments'] = array();
while ($resultArr = mysqli_fetch_assoc($check1)) {
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_content'] = $resultArr['comment_content'];
$json['comment_poster'] = $resultArr['comment_poster'];
$json['comment_datetime'] = Agotime($resultArr['comment_datetime']);
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
$json['streamdata_comments'] = $json;
}
/***** USERS *****/
$check = "SELECT * FROM users WHERE id=".$following_string."";
$check1 = mysqli_query($mysqli,$check);
$json['users'] = array();
while ($resultArr = mysqli_fetch_assoc($check1)) {
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
$json['users'] = $json;
}
echo json_encode($json);
}
?>
You're fetching unrelated data, so you can't use a join at the SQL level.
But JSON couldn't care less WHAT you feed it, or how. Just build the appropriate PHP-level data structure, e.g.
$data = array();
$data['streamdata'] = array();
... insert data from 'streamdata' query...
$data['streamdata_comments'] = array();
... insert comment data ...
$data['users'] = array();
... insert user data ...
which will give you a 3-way array containing the data from each of your queries. You then pass that entire $data structure to json_encode, and boom - you've got your 3 unrated queries in a single data structure, without every touching an SQL join.
Some previous answers have suggested that you can't join unrelated tables, but these are clearly not unrelated tables. The streamdata and streamdata_comments tables are quite closely related, and the users table maps user ID values in the other tables to names.
At the SQL level, these can be combined easily:
SELECT d.*, c.*, u.*
FROM streamdata AS d
JOIN streamdata_comments AS c ON d.streamitem_ID = c.comment_streamitem
JOIN users AS u ON u.user_id = c.comment_poster
WHERE c.comment_poster = '$following_string'
AND d.streamitem_id < '$lastID'
AND (d.streamitem_target = '$following_string' OR
d.streamitem_creator = '$following_string');
Whether the result makes sense for wrapping into a JSON string is a different matter, on which I can't pontificate. This would give you one record from the comments information for each comment associated with each stream item.
You are fetching unrelated data. Joining data is only usefull when the data to join has a relation.
You can't join apples, cows and monkeys.
I know the $downloadfile - and I want the $user_id. By trial and error I found that this does what I want. But it's 3 separate queries and 3 while loops. I have a feeling there is a better way. And yes, I only have a very little idea about what I'm doing :)
$result = pod_query("SELECT ID FROM wp_posts WHERE guid LIKE '%/$downloadfile'");
while ($row = mysql_fetch_assoc($result)) {
$attachment = $row['ID']; }
$result = pod_query("SELECT pod_id FROM wp_pods_rel WHERE tbl_row_id = '$attachment'");
while ($row = mysql_fetch_assoc($result)) {
$pod_id = $row['pod_id']; }
$result = pod_query("SELECT tbl_row_id FROM wp_pods_rel WHERE tbl_row_id = '$pod_id' AND field_id = '28'");
while ($row = mysql_fetch_assoc($result)) {
$user_id = $row['tbl_row_id']; }
Assuming I am understanding your queries correctly, this should work:
SELECT wp.ID, wpr.pod_id, wpr.tbl_row_id
FROM wp_pods_rel AS wpr
JOIN wp_posts AS wp
ON wp.ID = wpr.tbl_row_id
WHERE wpr.field_id = '28'
AND wp.guid LIKE '%/$downloadfile'
SELECT wp_posts.ID, wp_pods_rel.pod_id, wp_pods_rel.tbl_row_id
FROM wp_posts
JOIN wp_pods_rel ON wp_posts.ID = wp_pods_rel.tbl_row_id
WHERE wp_posts.guid LIKE '%/$downloadfile' AND wp_pods_rel.field_id = '28'