Querying database and putting two columns of each row into an array? - php

I have a sql database with table "profile_values" (yes, it's a Drupal db), and I would like to pull the user's name, title and company id with one query. (I have done this in the past with three queries, but I'd like to do it in one.)
| fid | uid | value
| 4 | 100 | john
| 8 | 100 | doe
| 9 | 100 | web developer
| 22 | 100 | D3239GE77
I used different field id's (fid) to show that there can be field id's between the rows that I want to pull, but the field id will not change, so 4 will always be first name, 8 would be last name, 9 would be title, and 22 would be company id.
MY FIRST ATTEMPT:
$result = mysql_query("SELECT value FROM profile_values WHERE uid = '$uid' ORDER BY fid ASC");
while($row = mysql_fetch_array($result)) {
$userinfo[] = $row['value'];
$firstname = $userinfo[0];
$lastname = $userinfo[1];
$title = $userinfo[10];
$companyid = $userinfo[12];
}
But this method won't work, because, depending on the optional fields that users will have filled out, there may be more or less fields between.
I need a way to say, "In this array, if fid = 4, $firstname = value

$result = mysql_query("SELECT fid, uid, value FROM profile_values WHERE uid = '$uid' ORDER BY fid ASC");
$user = array();
while ($row = mysql_fetch_array($result)) {
switch ($row['fid']) {
case 4:
$key = 'firstname';
break;
case 8:
$key = 'lastname';
break;
case 9:
$key = 'title';
break;
case 22:
$key = 'company_id';
break;
default:
continue 2; // 2 required when using switch inside loop
}
$user[$key] = $row['value'];
}

I would try the following:
$result = mysql_query("SELECT fid, value FROM profile_values WHERE uid = '$uid' ORDER BY fid ASC");
while($row = mysql_fetch_assoc($result)) {
switch ((int)$row['fid']) {
case 4:
$firstname = $row['value'];
break;
case 8:
$lastname = $row['value'];
break;
case 9:
$title = $row['value'];
break;
case 22:
$companyid = $row['value'];
break;
}
}
Then, I would be using isset() to check whether the variables exists, e.g. isset($lastname)
Hope this helps

Here is an approach that do not require a switch statements or ifs. It's based on an array where you previously map the table's fids to the keys on your destination array:
$fieldMap = array(
4 => 'firstname',
8 => 'lastname',
9 => 'title',
22 => 'companyid'
);
$userinfo = array();
$result = mysql_query("
SELECT fid, value
FROM profile_values
WHERE uid = $uid
ORDER BY fid ASC
");
while($row = mysql_fetch_array($result)) {
$fieldKey = $fieldMap[$row['fid']];
$userinfo[$fieldKey] = $row['value'];
}
Below is my original suggestion, where we pivot the results to get a "regular" table format, instead of a property table format:
SELECT
p1.value AS first_name,
p2.value AS last_name,
p3.value AS title,
p4.value AS company_id
FROM profile_values p1
LEFT OUTER JOIN profile_values p2
ON p2.uid = p1.uid
AND p2.fid = 8
LEFT OUTER JOIN profile_values p3
ON p3.uid = p1.uid
AND p3.fid = 9
LEFT OUTER JOIN profile_values p4
ON p4.uid = p1.uid
AND p4.fid = 22
WHERE p1.uid = $uid AND p1.fid = 4
This is more expensive for SQL then the way you're currently doing it, but it will allow you to fetch data from multiple users more easily (just change p1.uid = $uid to, e.g., p1.uid IN (2, 6, 29).

Related

Sum fields from different tables per userID

Need your help.
php, mysql
I have the following project.
I have two tables
**table 1**
user_id Plan
1 5
1 7
2 5
2 9
3 7
1 9
**table 2**
Plan Price
5 100
7 200
9 300
I must find the total cost of plans selected by one user
eg user_id = 2 must pay 400
I have already the following code, but this one adds the Price of all Plans in database in the above example total cost = 600
What am I doing wrong? :(
$totalcost = NULL;
$sql = "select SUM(Plan.Cost) as ANSWER FROM Plan";
$result = mysql_query($sql, $link) or die(mysql_error());
$totalcost = mysql_fetch_row($result);
$sql = "select * FROM Plan";
$result = mysql_query($sql, $link) or die(mysql_error());
$rows = mysql_num_rows($result);
$Plan = array();
if (is_resource($result)) {
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$Plan[] = $row;
}
}
You have to specify the user_id in your query, like:
$user_id = 2; // or get it from $_GET, $_POST...
$sql = "select SUM(Plan.Cost) as ANSWER
FROM Plan, Users
WHERE Users.Plan = Plan.Plan AND Users.user_id = $user_id";
You probably want to use LEFT JOIN in your query, so you can make something like this:
SELECT table1.user_id, table1.plan, SUM(table2.cost) FROM table1 LEFT JOIN table2 ON table1.plan=table2.plan WHERE table1.user_id = $user_id;
this way you can fetch results in 1 query and make database do all the work instead of looping through data in functions etc.
SQL left join tutorial

How do I get an array from DB

I've got a question.
I've got a table table1 like this:
ID | email | first_name | last_name
1 | bla | bladibla | bladibladibla
And with that, I got another table table2:
ID | table1_id | name | value
1 | 1 | foo | bar
2 | 1 | foo1 | bar1
3 | 1 | foo2 | bar2
My question: How do I get the results in php like this?
$array = [
id => 1,
email => bla,
first_name => bladibla,
last_name => bladibladibla,
data => [
[
name => foo,
value => bar
],
[
name => foo1,
value => bar1
],
[
name => foo2,
value => bar2
],
]
]
My solution that works for now, but does not seem the best way to handle it.
I have this now, but it does not seem to be the right way to do it, because in the first foreach loop, it's shooting a query to the db for every row in table1.
$query = "SELECT * FROM `table1`";
$results = $wpdb->get_results($query);
foreach($results as $result) {
$otherQuery = "SELECT * FROM `table2` WHERE `table1_id` = " . $result['id'];
$table2Results = $wpdb->get_results($otherQuery);
foreach($table2Results as $table2Result) {
// save all data in a new array just like I want it.
}
}
Try this :
$query = "SELECT * FROM `table1`";
$results = $wpdb->get_results($query);
$arr = []; // $arr = array();
foreach($results as $result) {
$temp = $result;
$otherQuery = "SELECT * FROM `table2` WHERE `table1_id` = " . $result['id'];
$table2Results = $wpdb->get_results($otherQuery);
foreach($table2Results as $table2Result) {
// save all data in a new array just like I want it.
$temp['data'][] = $table2Result
}
$arr[] = $temp;
}
print_($arr);
$data = array();
$i = 0;
foreach($results as $result)
{
$data[$i] = $result;
$otherQuery = "SELECT * FROM `table2` WHERE `table1_id` = " . $result['id'];
$table2Results = $wpdb->get_results($otherQuery);
$j = 0;
$data[$i]['data'] = array();
foreach($table2Results as $table2Result)
{
$data[$i]['data'][$j] = $table2Result;
$j++;
}
$i++;
}
print_r($data);
$query = "Select
t1.ID,t1.email,t1.first_name,t2.last_name,t2.name,t2.value
From
table1 t1
Inner Join
table2 t2
On t1.ID=t2.table1_id";
$results = $wpdb->get_results($query);
$arr1=[];
$arr2=[];
foreach($results as $result) {
$arr1[]=['id'=>$result['ID'],'email'=>$result['email'],
'first_name'=>$result['first_name'],
'last_name'=>$result['last_name'],'data'=>[]];
$arr2[]=['name' => $result['name'],'value' => $result['value']];
}
$arr1=array_unique($arr1);
$arr1['data'][]=$arr2;
You should be getting duplicates in the JOIN, since your example array shows that each table1 record is related to more than one table2 record. So doing multiple queries isn't going to avoid that. What you want, I think is something like:
$query = "SELECT * FROM table1 LEFT JOIN table2 WHERE table1.id = table2.table1_id";
$results = $wpdb->get_results($query);
foreach($results as $result) {
$table1_id = $result["table1.id"];
$entries[$table1_id]['id'] = $table1_id;
$entries[$table1_id]['email'] = $result["table1.email"];
$entries[$table1_id]['first_name'] = $result["table1.first_name"];
$entries[$table1_id]['last_name'] = $result["table1.last_name"];
$entries[$table1_id]['data'][] = array($result["table2.name"], $result["table2.value"]);
}
print_r($entries) // the full array of table1 entries with the sub-array of table2 entries per table1 entry.
By keying each array entry to the table1.id, you ensure that even when they are repeated, the table2 entries get added as new entries to the data array, while not creating an new array entry for the main "outer" table1 record.
If you don't want the table1.id key on the array itself (and have a simple 0-based indexed array, you could re-index after you are done in the loop like:
$entries = array_values($entries);

Get information from MySql Query and put it in PHP array

I have a table of which I must select information using a MySQLi Query and push it to the end of a PHP array.
The table is in this format:
table = friends
id user1 user1_id user2 user2_id datemade accepted
1 name1 1 name2 2 2015-05-27 03:24:32 1
2 name3 3 name2 2 2015-05-27 03:24:32 1
3 name3 3 name1 1 2015-05-27 03:24:32 1
4 name4 4 name2 2 2015-05-27 03:24:32 1
id = an auto_incrementing number to keep track of everything
user1 = the person's name that asks for friendship
user1_id = that person's special unique id
user2 = name of the person that accepts/decline's friendship
user2_id = that person's special unique id
datemade = the date it was made :P
accepted = did he accept? (don't worry about this)
I want to select all users that are friends with $u.
In this example, $u's id is 1 (name is name1).
After running the query it would push it to the end of friend_array.
So if I printed this array the output would be:
2, 3
Since, id=1 is friends with id=2 and id=3
What query should I do and how would I push that to an array (I know about about array_push but I do not know how to implement it)?
Please try this code. It will return the array for all user's friends.
$sql = "SELECT user1 AS user FROM friends UNION SELECT user2 AS user FROM friends";
$data = mysqli_query($sql);
while ($v = mysqli_fetch_assoc($data)) {
$sql = mysqli_query("SELECT * FROM `friends` where (user1 = '" . $v['user'] . "' or user2 = '" . $v['user'] . "')");
$arr = array();
while ($array = mysqli_fetch_assoc($sql)) {
if ($array['user1'] == $v['user']) {
$arr[$v['user']][] = $array['user2_id'];
} else {
$arr[$v['user']][] = $array['user1_id'];
}
}
}
I finally figured it out!
$sql = "SELECT COUNT(id) FROM friends WHERE user1_id='$log_id' AND accepted='1' OR user2_id='$log_id' AND accepted='1'";
$query = mysqli_query($db_conx, $sql);
$query_count = mysqli_fetch_row($query);
$friend_count = $query_count[0];
//echo($friend_count); //how many friends
if($friend_count < 1){
echo($u." has no friends yet");
} else {
$all_friends = array();
$sql = "SELECT user1_id FROM friends WHERE user2_id='$log_id' AND accepted='1' ORDER BY RAND()";
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
array_push($all_friends, $row["user1_id"]);
}
$sql = "SELECT user2_id FROM friends WHERE user1_id='$log_id' AND accepted='1' ORDER BY RAND()";
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
array_push($all_friends, $row["user2_id"]);
}
$friendArrayCount = count($all_friends);
}
So it first counts how many friends you have to check if you have any, if you do not a, temp. message appearing saying no friends. If you have some friends it will run a query to check what friends you have is both columns - user1_id and user2_id. It will then finally add everything to the $all_friends array and it then counts how many friends you have.
Thank you to everyone that helped!

select row from multiple tables failed

i have the following code.
i already try'd some sulotions from the search option, but nothing helped.
all tables have a row called: user_id with data in it, but still the query gives false
The $user variable has the value 29 and in my tables look like this:
+---------+---------+-------+-----------+
+ id | user_id | jaar + kenmerk |
+---------+---------+-------+-----------+
+ 1 | 29 | 2015 + standaard |
+---------+---------+-------+-----------+
$query = "SELECT buitenklimaat.user_id, kasklimaat.user_id, watermangement.user_id, energie.user_id FROM buitenklimaat, kasklimaat, watermangement, energie WHERE user_id = ".$user." AND kenmerk = 'standaard' AND jaar = ".date("Y")."";
$result = mysqli_query($conn, $query);
if($result === false) {
echo 'Query failed';
die();
}
else {
// do something
}
If the field user_id exists in more than one table, you need to prefix the field with the table name in your where clause, too. Otherwise your database will not know in which table it should look for the user_id field. But even after you fixed this error the query will probably not return what you want it to. Have a look at some SQL tutorials that cover the join syntax.
$query = "SELECT buitenklimaat.user_id, kasklimaat.user_id, watermangement.user_id, energie.user_id FROM buitenklimaat, kasklimaat, watermangement, energie WHERE <TABLENAME MISSING>.user_id = ".$user." AND kenmerk = 'standaard' AND jaar = ".date("Y")."";
You may need to join all those tables together to get the user_id condition to work properly:
$query = "SELECT buitenklimaat.user_id, kasklimaat.user_id,
watermangement.user_id, energie.user_id FROM buitenklimaat, kasklimaat,
watermangement, energie
WHERE buitenklimaat.user_id = kasklimaat.user_id
AND buitenklimaat.user_id = watermangement.user_id
AND buitenklimaat.user_id = energie .user_id
AND buitenklimaat.user_id = ".$user." AND kenmerk = 'standaard'
AND jaar = ".date("Y")."";

Get value in a table1 column with the column name is value in table2

I have two table, table2 has nameColumn that include name of table1 column like
table 1
id|check|status|...|
1 |abc |1 |...|
table2
|nameColumn|...|
|check |...|
|status |...|
I want get value in table1 with column name is value in table2 like
$sql="SELECT * FROM `table1` WHERE `id` = 1 ";
$result = mysqli_query($conn,$sql) or die (mysql_error ());
$rowTable = mysqli_fetch_array($result);
$s = "SELECT * FROM table2";
$r = mysqli_query($conn,$s);
while($row1 = mysqli_fetch_array($r)){
$columnName = $row1['nameColumn'];
$value = $rowTable["'".$columnName."'"]; // fail why?
//$value = $rowTable['check']; // working?
}
I don't know why $value = $rowTable["'".$columnName."'"]; fail the error like
Notice: Undefined index: 'check' ...
But if i using direct like $value = $rowTable['check']; // working why?
How to fix that thanks
its failing because your adding unnecessary ' char to it. try the code below
$value = $rowTable[$columnName];
$value = $rowTable['".$columnName."'];

Categories