Ok i have two tables with a left join. Let call table one "people" and the second table "dog". I have left joined the tables by an id:
"SELECT * FROM people
LEFT JOIN dog ON people.PK = dog.fk";
My problem is that both tables have a column title "name." When i echo back out the $_POST['name'] variable it give the same value for both fields I tried
echo $_POST['people.name']
echo $_POST['dog.name']
but this isn't returning any data so this must be incorrect. Can someone help me fix my problem without having to change my column names. Thanks you.
The $_POST superglobal contains data submitted from a form. It does not contain data from database queries. You probably do something like this (pseudocode):
$result = database_query (
"SELECT * FROM people LEFT JOIN dog ON people.PK = dog.fk"
);
The data you want is now contained in the variable named $result. How you access it will depend on your database access method, but typically you would fetch a row from the result object, perhaps as an associative array.
$row = database_fetch_assoc($result);
Then the array $row would contain your data.
echo $row['name'];
You might need to alias the column names in the query in order to be able to access the values of both name columns.
Alias the column names and don't use SELECT * but specify columns manually:
SELECT people.name AS people_name, dog.name AS dog_name
FROM people
LEFT JOIN dog ON people.PK = dog.fk
Then you can access the fields through ['people_name'] and ['doc_name'].
Depending on your table structure and which field you actually need you could also SELECT table1.*, table2.somecol AS t2_somecol - that's handy if you need everything from the first table but only a few fields from the second one.
Oh, and you really shouldn't put stuff into $_POST. It's meant to be populated by PHP with POST data - and data coming from your DB is not really POST data.
Related
Is it possible to get the list column names from a query in IBM db2?
Consider a very simple example I want the column names fetched by following SQL;
select * from db.t1,db.t2 where t1.id = t2.id
Actually I know how to get column names from a a single table. But facing difficulties to get column names from such scenario.
I want the list of columns as an Array in PHP. It can be done if I just add "FETCH FIRST 1 ROW ONLY" as the end of the SQL, and run it. Then from result set I can get the columns.
But if there is no data then also I need the list of columns. How to achieve that?
Any help would be great for me.
You can use db2_num_fields() to determine the number of columns in the result set, then loop over them and call db2_field_name() to obtain the names.
You could always just do something like
describe select * from tablea, tableb
I need to be able to pinpoint a value in a MySQL table which is defined by two variables.
On the frontend of the site, there is a form which accepts a variety of fields. For this example let’s focus on these two:
Account Number
Account Name
I have developed a script which will use an ajax script to check the “Account Number” once entered and if it finds a match will display the “Account Name” when the user tabs out of the field.
The difficulty is to find a single result from the format of the database tables. For example:
”SELECT * FROM example_table WHERE name=’$accountnumber’”
Provides a list of all the values that equal the account number, but does not provide any record of the account name.
”SELECT * FROM example_table WHERE name=’$accountname’”
Provides a list of all the values that equal the account names, but does not provide any record of the account number.
The $record value is the only common thread between $accountnumber and $accountname.
So all in all, I need assistance creating the loop which can first take the $accountnumber value to find the $record value associated with that number. Secondly it will take the determined $record value and match it to the $accountname value. There is only one $accountnumber and $accountname value per unique $record value.
UPDATED: There have been several good comments on this question. To help provide more background, there is only one table. The best discriminator available seems to be the title value. Here is a link to the table snippet to view in greater detail:
https://docs.google.com/file/d/0By2lFlhEzILjbE1uT1hkVURmczA/edit?usp=sharing
So ultimately in this sample, a user would type 246802 and the result that is filtered out would be Fred’s Account.
Sounds like these are in the same table? Is there any discriminator to tell you whether name holds an accountnumber or accountname?
In any even, with the following assumptions you could try an ugly self join:
There are only two records with the record ID you want
these are multiple columns in the same table holding different information in the ambiguous column names
there is no better way to discriminate the record type
If so, something like this self-join should get you started:
SELECT t2.name as accountnumber from example_table as t1
INNER JOIN example_table as t2 on t1.recordID=t2.recordID
WHERE t1.name='$accountname'
EDIT Note - if my assumptions are correct and if this is data you are inheriting, I feel for you and you should look to improve it's structure. If you are designing it like this, you may want to think about it some more first.
EDIT 2
You probably want to put an index on the name column (this is the discriminator I would used based on your example).
Your query can be something like this:
SELECT t1.value as accountnumber,t2.value as accountName from example_table as t1
INNER JOIN example_table as t2 on t1.record=t2.record
WHERE t1.name='accountNumber' and t2.name='accountName'
See this SQL Fiddle: http://www.sqlfiddle.com/#!2/97c2f/1
I'm currently trying to write a simple ORM with PHP and mysql. I want the orm class to be able to work with joined tables.
So here's my problem, the following code shows how I map the data the query yields into an array.
public function execute_query($db_connection)
{
$query = '';
foreach($this->sql_query as $query_part)
$query .= $query_part;
$result = $db_connection->query($query);
while($row = $result->fetch_assoc())
{
array_push($this->m_Data, $row);
}
}
db_connection is a mysqli object.
sql_query contains all the different query parts (e.g. sql_query['join'] etc.).
m_Data is the array that contains the data read from the db.
My specific problem now is when I'm using a join statement in my query this function will just override fields with the same name in my m_Data array. Also if I dont save the name's of the table the specific field data is coming from, I later can't update the tables with the same join statement.
tl,dr. I need to be able to not only save the table data like this: m_Data{ 'field_name' => 'value' } but I also need to save the table name the field is selected from. I could then save the data like this m_Data{ 'table_name.field_name' => 'value' } which enables me later to generate a query to update the joined tables successfully.
I cant seem to find any information on how to get the origin table name for each field I pull out of the result.
If it isnt possible with mysqli I'd much appreciate it if you point me in the right direction.
extra short problem statement:
I need to get a result set and read each row seperatly. For each row I need the following information for every field selected: field_name, table_name, value.
There must be a simple answer to this but I seem to be searching for the wrong keywords to find a solution.
I hope I've written this understandable enough.
Seems to me that you should store table column values in an object, so if you have a related table, the column values would be stored in a separate object - and so would not interfere with the values in your primary table.
In general you might work with the ORM this way:
// Make joined query
$rows = ...
foreach($rows as $row)
{
// $row just refers to the primary table
echo $row->id;
// You get a many:1 related table this way
echo $row->getRelatedRow()->value;
// You get a 1:many rows this way
$rows = $row->getOtherRelatedRows();
}
Depending on how you set up your query options, getting related data may or may not initiate further SELECTs to get the required data.
mysqli_result::fetch_fields has useful things:
http://www.php.net/manual/en/mysqli-result.fetch-fields.php
table
orgtable
field type
etc
I'm trying to do a customizable and extendable profile system for my CMS. From the user perspective it is straight forward, but for the admin I want all data, including the profile data, to be searchable. Profile fields may be added by "plugins", which may also add new fields to search on. I don't know if what I'm trying to do with MySQL to make this work is possible or if I'm going at it completely the wrong way.
So I have the users stored in one table (users), with columns for id, email, password and access_level.
I then have another table with profile information (profiles), stored as user_id, parameter and value. The parameter could eventually be put into a separate table again (so it isn't repeating itself), but for now I'll leave it like this.
The parameter and value are basically the profile data. For example, parameter may be "age" and the value may be "22".
What I want to try and do, is select the users table, with the profile information joined so the parameter is mapped to an additional column. So it ends up like so, straight from MySQL:
id email password access_level age
1 a#a.com ***** 1 22
2 b#b.com ***** 2 25
3 c#c.com ***** 2 25
I've been looking at pivot tables all afternoon, but from all I can see the "column name" is pre-defined. In this case I want the "column name" to come from the row itself.
If it isn't possible to do it with a single query, what other methods are there? I'm using PHP if the best method is to do it via that.
Any suggestions would be much appreciated. :)
Well, if you need to know the column names in advance, you can query the information_schema database:
SELECT COLUMN_NAME
FROM information_schema.COLUMNS
WHERE TABLE_NAME='your table'
However, that gets the raw column names. If you're aliasing in your query, you'll have to fetch them indirectly:
SELECT somefield AS alias1, otherfield AS alias2
FROM ...
and then
$stmt = mysql_query($query);
$first = true;
while($row = mysql_fetch_assoc($stmt)) {
if ($first) {
$column_names = array_keys($row);
... display column names here
$first = false;
}
... output row here
}
Here is my table setup:
employee: Employee information, name, address, etc...
group: List of distribution groups.
employee2group: table that links employees to multiple groups.
I have it setup this way so I can add groups in the future, without having to add columns to my employee table. This may seem like common sense to you all, but I just started with PHP a couple months ago, so everything is still new and confusing to me.
So, I'm working on my update form, which will display a list of check boxes that is populated with a simple SELECT * FROM group query. The idea is to show the ones that an employee is part of as "checked" when I view the employee in the update form.
Currently, my while loop to show the list of check boxes is this:
<?php
$group_list_query = "SELECT * FROM group"
$group_list_result = mysql_query($group_list_query, $cmsWrite)
while ($row = mysql_fetch_assoc($group_list_result)) {
echo "<input type=\"checkbox\" name=\"distro_{$row['group_name']}\"> {$row['group_name']}";
}
?>
Pretty simple. I might have some syntax errors in there, but in my code they don't exist, because it works fine.
So what I need to do, is run another query that returns ONLY the names of the groups that the employee belongs to:
SELECT group.group_name
FROM group JOIN employee2group ON group.group_id = employee2group.group_id
WHERE employee2group.employee_id ='{$_GET['employee_id']}'
Then, I need to compare the two queries, and output a normal check box when there isn't a match, and output a checked check box when there is a match.
I tried doing a while statement that set $row = query1 and $row2 = query2, and compare the $row and $row2 values, but then it only returned instances where both queries had results, instead of all of them.
I hope this makes sense, I've been trolling the internet for a while, and haven't found anything that pertains to my problem.
Thanks for reading!
Two solutions :
1 : Get a array of the groupIds that user is a member of, then when looping through the group list. Check if the id is in that array with in_array, if it is dont display the check box
2 : Do a left join on the employee2group table and check if the value = null or not, if its null display the check box.
--
Off question topic but you should also look at using bound paramaters rather than just including them inthe sql statement like that, leaves it open to sql injection otherwise.