Foreign keys output PHP - php

I'm tring to get a hold of foreign keys, as I need to use it for a gallery, where each uploaded image is assigned to a photographer, these photographers also need to be showed in the menu.
I have followed this guide and everything went well. I now need to output the data with PHP - this I can't figure out.
<?php
$sql = "SELECT * FROM borrowed WHERE employee.id = 'Reck' JOIN employee ON employee.id = borrowed.employeeid";
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($result)) {
?>
<? echo $row['lastname']; ?>
<?php
}
?>
I get the error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /Applications/MAMP/htdocs/galleri/test.php on line 12
Line 12 is the while loop.

An error within your query please refer query structure How to use joins
Within your query join is after where condition but it must be before where. It should be like this
$sql = "SELECT * FROM borrowed JOIN employee ON employee.id = borrowed.employeeid WHERE employee.id = 'Reck'";
and your code
<?php
$sql = "SELECT * FROM borrowed JOIN employee ON employee.id = borrowed.employeeid WHERE employee.id = 'Reck'";
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($result)) {
echo $row['lastname'];
}
?>

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'];
}

Subqueries for php

sorry if this might be a duplicate question but im desperatly needs help for project submission.
I have a database carpark where i have 2 table within which is carpark_availability and history.
From my code, im able to get a field "development" from table carpark_availability.
I would like to ask on how to structure my queries if i want to select * from c where my h.development = c.development.
As shown below is my code:
<?php
session_start();
$con = new mysqli('localhost','root','','carpark_project');
$dev = $_SESSION["development"];
echo "Development: ";
echo $dev;
$sql = "select * from carpark_availability where
carpark_availability.Development IN (select history.development
from history where
history.Development = '$dev' )";
//$sql = "select * from carpark_availability where development = '$dev'";
//$sql = "select * from carpark_availability where (select Development
//from history where Development= '$dev'";
$result = $con->query($sql);
while($row = $result ->fetch_assoc())
{
echo "Development: ";
echo $row["Development"]. "</br>";
echo $row["Area"]."</br>";
echo $row["weekday1"]."</br>";
}
?>
A join is much easier on the eye than a subquery.
SELECT c.*
FROM carpark_availability c
INNER JOIN history
USING (development)
GROUP BY development;
I'm guessing you are getting an error because your query is returning no results so $result is set to boolean false. You have nothing in your code to check for that so you are trying to call fetch_assoc() on it

Accessing rows from a mysqli join query in 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);

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 error: "supplied argument is not a valid MySQL result resource in"

So writing my first PHP website with a web store. I have written a piece of code that is suppose to select the products database with all the products of a category, and then display an image using the same product_id selecting the front picture.
Code is as follows:
<?PHP
include_once "db.php";
$result = "(select * FROM products WHERE product_type = 'weddingdressaline') inner join (select * FROM images WHERE postion = 'front') images on products.product_id = images.product_id";
while($row = mysql_fetch_array($result)) {
$content = $row['image'];
header('Content-type: image/jpg');
echo $content;
echo $row['price'];
}
mysql_free_result($result);
mysql_close();
?>
But when I run the script I get the following errors:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
result resource in **/weddingdressaline.php on line 4
Warning: mysql_free_result(): supplied argument is not a valid MySQL
result resource in **/weddingdressaline.php on line 11
Now I'm pretty sure that the reason for the second error is because the first error is occuring. Any help you could give me would be really appreciated.
You're not sending your query to the SQL database - it's just a string. You'll need to call mysql_query on it, like so:
$result = mysql_query("(select * FROM products WHERE product_type = 'weddingdressaline') inner join (select * FROM images WHERE postion = 'front') images on products.product_id = images.product_id");
As Pekka points out, though, you should be checking for errors as well.
You are missing the mysql_query. The $result line should read the following:
$result = mysql_query($your_query_here);
You are not querying your database …
$result = mysql_query("(select * FROM products WHERE product_type = 'weddingdressaline') inner join (select * FROM images WHERE postion = 'front') images on products.product_id = images.product_id");
while ($row = mysql_fetch_array($result))
{
$content = $row['image'];
header('Content-type: image/jpg');
echo $content;
echo $row['price'];
}
You forgot to use mysql_query()
$result = mysql_query("(select * FROM products WHERE product_type = 'weddingdressaline') inner join (select * FROM images WHERE postion = 'front') images on products.product_id = images.product_id");

Categories