Accessing rows from a mysqli join query in php - php

I have the following code:
// db connection info set up earlier
$sql= "SELECT `TABLE_1.ID`, `TABLE_2.ID`, `POTATO` FROM `TABLE_1.ID` LEFT JOIN `TABLE_2` ON `TABLE_1`.`ID` = `TABLE_2`.`ID_OF_OTHER_TABLE`;";
$rows = mysqli_query($connection, $sql);
foreach ($rows as $row){
$potato = $row["POTATO"];
$id = $row["TABLE_2.ID"];
}
I can't get TABLE_2.ID. I've tried to doing a print_r to get the proper format, but it says it's a mysqli object and I don't get much more info than that. However, I can get potato. So I'm guessing it's a calling syntax issue, but I've searched multiple sites (stack and google included) and not found a clear answer. So, what do I need to do instead of
$id = $row["TABLE_2.ID"];
?

Assign aliases to the columns with the same name.
$sql= "SELECT `TABLE_1`.`ID` AS t1_id, `TABLE_2`.`ID` AS t2_id, `POTATO`
FROM `TABLE_1.ID`
LEFT JOIN `TABLE_2` ON `TABLE_2`.`ID_OF_OTHER_TABLE` = `TABLE_1`.`ID`;";
$rows = mysqli_query($connection, $sql);
foreach ($rows as $row){
$potato = $row["POTATO"];
$id = $row["t2_id"];
}

You can't left join a table with itself, you also cannot have a table that isn't joined = something from another table that cannot be joined to itself.
This will work:
// db connection info set up earlier
$sql= "SELECT TABLE_1.ID, TABLE_2.ID, POTATO
FROM
TABLE_1.ID
LEFT JOIN TABLE_2 ON TABLE_1.ID = TABLE_2.ID";
$rows = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_assoc($rows)) {
echo ($row['ID']);
}
mysql_free_result($rows);

Related

Do I need a left, natural or simple join in SQL?

I am new to PHP coding and just trying to fix some functionality on my site that was left over from the lead developer.
The site, [Vloggi], is a marketplace. So I need to show the name of the job poster in the assignments page . The table I have the jobs in only has the ID, not the name.
So I need a join, but I've tried and it breaks the entire site.
The SQL has 17 tables, I need to display the User Name (usr_name) contained in table 3, the organisation contained in table 7 (usrg_orgname) with the job posting user (vlop_usr_id) details in table 14.
The primary key is users.usr_id, which is linked to users_gor.usrg_usr_id and vlog-ops.vlog_usr_id.
Table 3: users
usr_id, usr_email, usr_password, usr_fbuser, usr_fbtoken, usr_name, usr_loc_name, usr_loc_lat1, usr_loc_lon1, usr_loc_lat2, usr_loc_lon2, usr_status, usr_gor, usr_vgr, usr_token, usr_regtoken,
table 7: users_gor
usrg_usr_id, usrg_creditops, usrg_creditvlog, usrg_creditvlogette, usrg_destination, usrg_orgname, usrg_orgtype, usrg_location, usrg_website, usrg_jobtitle, usrg_phone, usrg_address1, usrg_address2, usrg_state, usrg_postcode, usrg_country
Table 14: vlog-ops
vlop_id, vlop_title, vlop_description, vlop_tags, vlop_deadline, vlop_quantity, vlop_quantityposted, vlop_vser_id, vlop_usr_id,vlop_loc_name, vlop_loc_lat1, vlop_loc_lon1, vlop_loc_lat2, vlop_loc_lon2, vlop_campaign, vlop_rules, vlop_tips, vlop_status
So in main.php i have written the following Sql lookup
in main.php, I have the following SQL lookups:
$sql = "SELECT * FROM users_gor WHERE usrg_usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users_gor = $rows[0];
$sql = "SELECT * FROM users_vgr WHERE usrv_usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users_vgr = $rows[0];
$sql = "SELECT * FROM users WHERE usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
$sql = "SELECT * FROM vlog-ops WHERE vlop_usr_id ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
$sql = "SELECT usr_name AS vlop_usr_name FROM users WHERE usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
And then in the page template itself, I have written
<?php echo $vlop['vlop_vser_id'] ?>
<?php echo $vlop['vlop_usr_name'] ?>
The first one works, the second doesn’t. What I want eventually is to display the user name and the organisation name in a table.
Whenever I try a JOIN or a NATURAL JOIN or a LEFT JOIN it breaks and the entire site goes blank.
Any help for a newbie would be appreciated with a million thanks.
When you use JOIN you need to specify how you're joining them.
In the query below I'm assuming you're looking for the fields in bold from your question.
$query='SELECT u.usr_name, g.usrg_orgname, v.vlop_usr_id FROM users u
JOIN vlog-ops v on u.usr_id = v.vlop_usr_id
JOIN users_gor g on u.usr_id = g.usrg_usr_id';
I believe I got the name of the fields right but if not just replace them with the correct ones.
Once you have the data fetched, you just loop through the results:
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
echo 'User name = ' . $row['u.usr_name'];
echo 'Org name = ' . $row['g.usrg_orgname'];
echo 'Job posting user id = ' . $row['v.vlop_usr_id'];
}

Replaceing mysqli query in while loop with one query using JOIN

I often read that mysql(i) queries used in while loops are not really performance friendly and I'm going to rewrite my code because I think it get better. But here's my question if a JOIN can work here. It's a single post viewing function but you should see every comment which got posted below. I got the comment loop in the loop which the post is printed.
<?php
$result = (empty($_GET['hash'])) ? $_GET['hash'] = '' : mysqli_query($conn, "SELECT * FROM `userposts` WHERE `hash`='".$_GET['hash']."' LIMIT 1");
while($rows = mysqli_fetch_array($result)){
//Output of single post
$commentresult = mysqli_query($conn, "SELECT * FROM `comments` WHERE `postid`='".$rows['id']."'");
while($commentrows = mysqli_fetch_array($commentresult)){
//Output of all comments
}
}
So I think it gets better but the query with JOIN should be like:
$result = (empty($_GET['hash'])) ? $_GET['hash'] = '' : mysqli_query($conn, "SELECT * FROM `userposts` JOIN comments ON userposts.id = comments.postid WHERE `hash`='".$_GET['hash']."' LIMIT 1");
But if I'm trying to post the data of the comments in the while loop which is the singlepost printed it just prints one comment. So what can I do?
regards
Your code is a bit of a mess. You are sometimes call mysql_fetch_results with a string, which is weird.
What you want is this:
"SELECT * FROM comments LEFT JOIN userposts ON comments.PostID = userposts.ID WHERE userposts.Hash = '$_GET['hash']'"
EDIT: sorry, you want LEFT JOIN with comments on the left. Gives you all the comments
EDIT 2: I set this up and it worked as I expected, even with multiple posts with the same hash.
<?php
$hash = $_GET['hash'];
$result = mysqli_query($conn, "SELECT * FROM comments LEFT JOIN userposts ON comments.PostID = userposts.ID WHERE userposts.Hash = '$hash'");
if ( $row = mysql_fetch_array($result)) {
// output of post.
// output first comment
}
while($row = mysqli_fetch_array($result)){
//Output other comments
}
?>

php - return multiple values to from mysql

I'm dealing with a junction table for a many to many relationship between products and categories. With this particular function I'm attempting to take in a product_ID variable and get all associated category names in an array. However, with the current setup I'm only getting one category per product ID when I know several have 2. Any thoughts? Also anyone know of a good simple solution to more visually keeping track of M2M relationships in mysql?
//INPUT PRODUCT ID, GET ASSOCIATED CATEGORIES
function productcat($pid) {
global $sql;
$query = "SELECT * FROM Product_Category WHERE Product_ID = '$pid'";
$result = mysqli_query($sql, $query);
$catidarray = array();
while($row = mysqli_fetch_array($result)) {
array_push($catidarray, $row['Category_ID']);
}
foreach($catidarray as $i) {
$query = "SELECT * FROM Categories WHERE Category_ID = '$i'";
$result = mysqli_query($sql, $query);
$namearray = array();
while($row = mysqli_fetch_array($result)) {
array_push($namearray, $row['Name']);
}
}
return $namearray;
}
There is something wrong with your function.
In your second foreach, you put the variable $namearray inside the loop which on every run resets its value to empty array $namearray = array();. Just put that outside the foreach:
//--> put it here
$namearray = array();
foreach($catidarray as $i) {
$query = "SELECT * FROM Categories WHERE Category_ID = '$i'";
$result = mysqli_query($sql, $query);
while($row = mysqli_fetch_array($result)) {
array_push($namearray, $row['Name']);
}
}
And, I just want to make some suggestions on your function. Since you have the junction table, you don't really need to have a separate query for product and category in order to get your desired values from those tables.
Just do the INNER JOIN to maximize the use of your table relations.
Use your junction table Product_Category because that's the real purpose why created that.
SELECT *
FROM Product_Category AS a
INNER JOIN Category AS b
ON a.Category_ID = b.Category_ID
WHERE Product_ID = $pid
In your function, you may try this: havent tested but hope this will give you idea.
//INPUT PRODUCT ID, GET ASSOCIATED CATEGORIES
function productcat($pid) {
global $sql;
$query = "SELECT *
FROM Product_Category as a
INNER JOIN Category as b
ON a.Category_ID = b.Category_ID
WHERE Product_ID = {$pid}";
$result = mysqli_query($sql, $query);
$namearray = array();
while($row = mysqli_fetch_array($result)) {
array_push($catidarray, $row['Name']);
}
return $namearray;
}
Then that's it :)
And by the way, in the latest version of php, mysql_ functions are already deprecated. Much better if you will be going to use PDO or MySQLi.
Check this also: PDO vs. MySQLi

How To Use Key Value in Stored Array in New Select Query

I'm working in PHP and MySQL to create and list a membership directory. I have three tables - company, contact and branch. Companies have Contact people, and some but not all companies have Branches, which also have Contact people. I am using LEFT JOIN in my first query to connect the contact people to their respective company, and loading the results into an array, which works using the following code:
// Retrieve all the data from the "company" table
$query = "SELECT * FROM company LEFT JOIN contact ON company.company_id = contact.company_id WHERE comp_county = 'BERNALILLO' ORDER BY company.comp_name, contact.cont_rank";
$result = mysql_query($query)
or die(mysql_error());
// Build the $company_array
$company_array = array();
while($row = mysql_fetch_assoc($result)) {
$company_array[] = $row;
}
Now I am trying to figure out how to run a second query, which needs to select from my branch table all branches whose company_id match the company_id stored in my above array: $company_array. I then want to store the results of the second query into a second array called $branch_array. I have tried this:
// Retrieve all the matching data from the "branch" table
foreach($company_array as $row) {
$query2 = "SELECT * FROM branch LEFT JOIN contact ON branch.branch_id = contact.branch_id WHERE branch.company_id = '".$row['company_id']."' ORDER BY branch.br_name, contact.cont_rank";
$result2 = mysql_query($query2)
or die(mysql_error());
}
// Build the $branch_array
$branch_array = array();
while($row2 = mysql_fetch_assoc($result2)) {
$branch_array[] = $row2;
}
But this does not seem to work... Can anyone give me an example of how to do this? The query needs to run so that it checks each different company_id in my $company_array for a match in the branch table - hopefully the question makes sense. Thanks.
i think your while should be inside your foreach statement so that your $branch_array can be filled with results of all company_id values, not only the last one :
foreach($company_array as $row) {
$query2 = "SELECT * FROM branch LEFT JOIN contact ON branch.branch_id = contact.branch_id WHERE branch.company_id = '".$row['company_id']."' ORDER BY branch.br_name, contact.cont_rank";
$result2 = mysql_query($query2)
or die(mysql_error());
// Build the $branch_array
$branch_array = array();
while($row2 = mysql_fetch_assoc($result2)) {
$branch_array[] = $row2;
}
}

Getting the table name of a row from a mysql query that grabs from multiple tables

I have some PHP/MySQL code that pulls data from multiple different tables (using Inner Joins). It looks something like this:
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($data)) {
echo $row[1];
}
So the code is simple enough, but what I want to do is echo the table each row is in inside of that while loop, since it could be in one of 2 tables.
I saw there was some old mysql functions like mysql_field_table and mysql_tablename that would do the trick, but they all seem to be deprecated.
Would appreciate any advice on how to accomplish this.
You could select the data with a special identifier for each table instead of using *
select table1.row1 as t1r1, table2.row1 as t2r1,..... from .....
And inside php you could look for the strings t1 and t2 and do stuff accordingly.
What you can do is echo more than one field from your result table (which hopefully now contains information from both the tables.
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($data))
{
echo $row[1] . " " . $row[2];
}
...and then $row[3] etc...
Or access the column name/field by the column name or alias provided by AS.
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_assoc($data))
{
echo $row["c_name1"] . " " . $row["c_name2"];
}
Where "c_name1" and "c_name2" are your column names.
Use an AS keyword to rename all columns.
$select_clause = '';
$tables = array('tblA', 'tblB');
foreach($tables as $tbl) {
mysql_query('SHOW COLUMNS FROM ' . $tbl);
while ($row = mysql_fetch_assoc())
$select_clause .= '`'.$tbl.'`.`'.$row['Field'].'` AS `'.$tbl
.'_'.$row['Field'].'`,';
}
$select_clause = substr($select_clause, 0, -1);
mysql_query('SELECT '.$select_clause.' FROM /*...*/ ');

Categories