Select one value of one colum of an array obtained with pdo - php

I have the following code :
$foo = $bdd->prepare($qry);
$foo->execute();
$result = $foo->fetchAll();
In $qry, i have a SELECT with a JOIN between tables beatles b et status s (on the columns status_id), such that the result is the following :
Code :
b.id b.firstname b.lastname b.status_id s.status_id s.status
0 John Lennon 0 0 Mort
1 Paul McCartney 1 1 Vivant
2 Ringo Starr 1 1 Vivant
3 George Harrison 0 0 Mort
(The first line is the columns' names in the tables, it isn't inside the result of the query)
I want to select in php only the s.status of ringo starr, for instance. How can I do that ?
Thanks

If you want to retrieve the value of status for Ringo Starr, but need the values of the other fields within that page, then (assuming the array has come back indexed by id), you could access it with $result[2]['status']. Otherwise, change your select statement to just select the values of id and status.
As a side note, in your SELECT statement you'll need to give aliases potentially for the b.status_id and s.status_id; when you join, the column names are taken and the table names basically ignored in terms of what is returned - so something like b.status_id AS b_status_id, s.status_id AS s_status_id would make sure you got the correct values for both of these. You may have done this already of course - it just looked as though you might have not, judging from the column names you gave.

I am not sure if you want to just pick one column from the existing result or issue a query that will get you only what you want. But a better defined query sound the most sensible
SELECT
[ your joins etc ]
WHERE b.firstname = 'Ringo'
AND b.lastname = 'Starr'
Or if you want to just get the Ringo Starr entry from your existing result
foreach ( $resultats as $result ) {
if ( $result['firstname'] == 'Ringo' && $result['lastname'] == 'Starr' ) {
echo 'Got him';
}
}

add WHERE clause with condition that satisfy your needs
alter fields clause leaving only one you need
use fetchColumn() instead of fetchAll()
You're set.

Related

I want to subtract 2 columns of two different tables

tbl_blood:
id|qty
1 14
2 15
3 16
tbl_blood_list:
id|blood_quantity
1 1
2 1
3 1
My question is the tbl_blood table's column qty should subtract the blood_quantity column in tbl_blood_list's table. I need codes that I can implement in my php mysqli.
I have tried this code but it really cannot work:
$add_inv = "UPDATE tbl_blood
SET qty=(qty - '$blood_quantity')
WHERE id='$minus_blood_id' ";
If i m not misjudging your question so you want to update join but in your table structure i can't find any common column if there is Any common column in both table so you can join and update your table in one statement i think id are common in both table if yes so try this
$pdo->query("UPDATE tbl_blood AS tb JOIN tbl_blood_list AS tbl ON (tbl.id = tb.id) SET tb.qty = (tb.qty - tbl.blood_quantity)")
Please let me know if there is any problem or i misjudge your issue
Hope it's help you.
There are more efficient ways to handle this kind of situation, you should consider a different structure for your program/tables, why having two separate tables when tbl_blood could be decremented directly.
With your current structure, the code below works:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=blood', 'user', 'password');
/* Retrieve values to update */
$result = $pdo->query('
SELECT tb.id, (tb.qty - tbl.blood_quantity) n
FROM tbl_blood tb
LEFT JOIN tbl_blood_list tbl ON (tbl.id = tb.id)');
/* Update */
foreach ($result as $row)
$pdo->query('UPDATE tbl_blood SET qty = '.(int)$row['n'].' WHERE id = '.(int)$row['id'].' LIMIT 1');
?>
Result:
tbl_blood
id|qty
1 13
2 14
3 15
Also:
You may consider harmonizing your field names (e.g. 'blood_qty' and not 'blood_quantity')
Make sure "qty" and "blood_quantity" fields are unsigned integers
Make sure too that both "id" fields are primary keys
You may add a timestamp field in both tables to keep track of updates

Search Two Tables & Concatenate Answer

I am trying to search two tables, match the results and then concatenate the answer... Only finding results >= today's date. This will then give the user the option to delete the selected from the DB. So...
Table 1 called Prog_name
id prog_name
1 Breakfast
2 Mid Morning
3 Afternoon
Table 2 called talk_ups
id date_tx prog_name (prog_name value = prog_name.id)
1 2017-06-30 2
2 2017-07-03 1
3 2017-07-01 3
The result I am after is something like: "01-07-2017, Afternoon". But I do also need the talk_ups.id to ensure it only deletes the correct record.
I managed to figure out how to get the name to match the talk_ups.prog_name value:
'$sql. = "SELECT talk_ups.prog_name, prog_name.id as progID, prog_name.prog_name as theName FROM prog_name, talk_ups WHERE talk_ups.prog_name = prog_name.id";'
But I can't figure out how to do the two searches and end up with the right result and how to separate out the results to then concatenate them.
You can use JOIN with WHERE condition, e.g.:
SELECT pn.id, pn.prog_name, tu.date_tx
FROM prog_name pn JOIN talk_ups tu ON pn.id = tu.prog_name
WHERE tu.date_tx > NOW();

MySQL - How to get counts of specific value from all the records

I have course table and I am storing completion status of users with 'A'. Now I want to get how many A is available from CompletionStatus field for all records.
I want this result: A = 5.
Course Table:
CourseRecordIdx User CompletionStatus
--------------- ---- --------------------
1 152 A___A_______________
2 147 AA_______A__________
I have tried with char_length but getting count with underscore and I want to get only total of A:
SELECT char_length(CompletionStatus) FROM `course` where CourseRecordIdx = 36
Any idea how to get result with select query?
Thanks.
You can try with this simplest way:
SELECT length(REPLACE("field_name","_","")) FROM `tbl_name`;
You can use LENGTH and REPLACE for that purpose :
SELECT LENGTH(CompletionStatus) - LENGTH(REPLACE(CompletionStatus, 'A', '')) as count_Char
FROM `course`
This basically counts how many characters are in that string, and then checks the difference between that number, and the number of characters with out the specific character.
I suppose the following will work, first replace all _ with ''.
After that use char_length() function.
SELECT CHAR_LENGTH(REPLACE(CompletionStatus,'_','') as totalA FROM course where CourseRecordIdx = 36;
You can write this query for this:
SELECT CourseRecordIdx,User,CompletionStatus,
ROUND (
(
LENGTH(CompletionStatus)- LENGTH( REPLACE ( CompletionStatus, "A", ""))
) / LENGTH("A")) AS count
from `course` where CourseRecordIdx = 36

mySQL search for id in array

I want to filter my SQL query with some array of IDs.
so I have IDs for example: 2,3,4 and activity_meta.value 1,2,5;
And I want to find every activity where it has id in activity_meta.value
SELECT DISTINCT a.*, u.user_email, u.user_nicename, u.user_login, u.display_name
FROM wp_bp_activity a
LEFT JOIN wp_users u
ON a.user_id = u.ID
INNER JOIN wp_bp_activity_meta
ON (a.id = wp_bp_activity_meta.activity_id)
WHERE a.is_spam = 0
AND a.hide_sitewide = 0
AND a.type != 'activity_comment'
AND (wp_bp_activity_meta.meta_key = 'activity_tagz' )
DESC LIMIT 0, 20
I want to add AND (1,2,3 IN wp_bp_activity_meta.meta_value)
I just dont know how to treat serialized array;
The value of activity_meta.value is not normalized. It would be a better choice, to create a second table, where you assign the meta tags to your element.
So, it would look like:
wp_bp_activity_id | meta
1 | 1
1 | 2
1 | 3
let's cal this table "meta_relation". Then you simple could either use a subselect, like this:
... WHERE wp_bp_activity.id in (SELECT wp_bp_activity_id FROM meta_relation WHERE meta in (1,2,5))
Or you could implement this with another join, like
... INNER JOIN meta_relation ON wp_bp_activitiy.id = meta_relation.wp_bp_activity_id
(will return 3 rows then for 3 matching tags)
... WHERE meta in (1,2,5)
... GROUP BY wp_bp_activity.id
(will remove any duplicate result and unwanted tags)
For your current scenario you could use a workaround. However this requires to build up the query programmatically:
For each "Tag", you want to find (i.e. 1,2,5) you need to add another or-condition.
To make sure you are not matching the 2 within 125 you can sourround it by ,.
To make sure, you are not missing the FIRST or LAST item (which has no leading / trailing , you need to concatenate the column with 2 more , in the first place:
Query then contains the following additional criterias.
SELECT
....
WHERE
...
AND
(
CONCAT(CONCAT(",", activity_meta.value ), ",") LIKE "%,1,%" OR
CONCAT(CONCAT(",", activity_meta.value ), ",") LIKE "%,2,%" OR
CONCAT(CONCAT(",", activity_meta.value ), ",") LIKE "%,5,%"
)
if you want all 3 tags to appear, use AND instead of OR.
in your example, this will match :
,2,3,4, against ,1,
,2,3,4, against ,2, //match
,2,3,4, against ,5,
Order and / or gaps don't matter with this approach.
(Depending on whether its a 10 User Website or a Million-Customer-Portal, you can use either. Preferred Solution is to normalize your table.)

Retriving an array of grouped elements in mysql (+php)

I need i bit of help with this query, so far i have this:
SELECT * FROM coupons WHERE discount_id = '1' AND client_username = 'Zara' GROUP BY winner_id
The table is like this
id client_username winner_id bdate discount_id destroyed
72 zara 1125405534 2012-11-11 03:34:49 4 0
71 zara 1125405534 2012-11-11 03:34:43 1 0
70 zara 1125405534 2012-11-11 03:34:27 1 0
I want to group the result by winner_id (its a unique user id) where discount_id is equal to some value and order by bdate, the think is I need the id bdate and destroyed value of each ocurrence of the user and also count the number of times winner_id appear, so the result needs to be a value (count of how many times winner_id appears), and 3 arrays (discount_id,destroyed,id).. But I have no idea how to retrive this in the way I need. Thanks for any help!
Two basic methods:
aggregate in mysql and "explode" in php
aggregate in PHP
number 1 involves using some aggregate functions in your query, like COUNT() and GROUP_CONCAT():
SELECT count(*) as num_wins, GROUP_CONCAT(discount_id, ',') as discount_ids ...
then in PHP, these GROUP_CONCAT columns can be "exploded" into arrays while looping over the results:
foreach($rows as $row) {
$discount_ids = explode(',', $row['discount_ids']);
// ...
}
number 2 is easier SQL, but uglier PHP. Basically just select all your rows, and then pre-process the results yourself. (I recommend the previous solution)
foreach($rows as $row) {
$results_tree[$row['winner_id']]['num_wins']++;
$results_tree[$row['winner_id']]['discount_ids'][] = $row['discount_id'];
// ...
}

Categories