Replaceing mysqli query in while loop with one query using JOIN - php

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
}
?>

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

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);

How to recall items from favourites table

I have a table of favourites with 'id' 'userid' and 'postid'. I'm trying to select all the entries in 'postid' when 'userid' = 1 for example.
I also have a table of posts with 'id' and others of content. I then want to select all the rows where a 'postid'='id' and then echo the content of those rows.
Essentially filtering the posts by which have been favourited by the user.
What I've got is
<?php
include 'connect.php';
$user = $_SESSION['id'];
$getfaves = mysql_query("SELECT postid FROM Favourites where userid='$user'") or die(mysql_query());
if ($rowfave = mysql_fetch_assoc($getfaves))
{
$faveposts = $rowfave['id'];
$getposts = mysql_query("SELECT * FROM Posts where id='$faveposts' ORDER BY id DESC");
while ($row = mysql_fetch_assoc($getposts))
{
$content = 'content';
echo ($content);
}
}
?>
(the $content = 'content'; is just an example, it's not what I'm actually using in my code)
Obviously this is incorrect, probably because I want to select a list of ids and then search for everything in that list, but I've only coded to look for one item. However I don't know how to correct this.
Thanks in advance for any assistance.
there is a more simple way to do that using just one sql query with the help of INNER JOIN.
so your query will be
SELECT POST.*
FROM `Favourites`
INNER JOIN `Post`
ON Post.id = Favourites.postid WHERE (Favourites.userid='$user')
ORDER BY Post.id DESC;
here is doc about INNER JOIN and its utilities
Please let me know if you need more help,
the php part:
<?php
include 'connect.php';
$user = $_SESSION['id'];
$sql="SELECT POST.*
FROM `Favourites`
INNER JOIN `Post`
ON Post.id = Favourites.postid WHERE (Favourites.userid='$user')
ORDER BY Post.id DESC";
$conn = new mysqli($servername, $username, $password,$dataBase);
$Result = $conn->query($sql);
while($row = $Result->fetch_assoc()) {
//do what you want with the $row, it contain ur resault
}
?>
feel free to test it and report the problem if there is one

obtaining comments for each post

hi I have to create a system of comments within various trhead I performed before and all the while the trhead 'while inside the comment and it works but is really slow and with a large number of threads often gives me timeout error how can I fix the problem?
function commenti($id) {
$query2 = "SELECT * FROM table2 WHERE numid='$id' ORDER BY id ASC";
$result2 = mysqli_query($conn,$query2);
if($result2->num_rows >0)
{
while($row2 = $result2->fetch_array(MYSQLI_ASSOC))
{
$idt2 = $row2['id'];
$testot2 = $row2['testo'];
return $testot2;
}
} else {
echo "No comment";
}
}
$query = "SELECT * FROM table1 where visualizza='1' ORDER BY id DESC";
$result = mysqli_query($conn,$query);
if($result->num_rows >0)
{
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$id = $row['id'];
$titolo = $row['titolo'];
$testo = commenti($id);
echo "$titolo $testo <br>";
}
}
mysqli_close($conn);
?>
I thought to use the join but if there are more duplicates also post comments
$query = "SELECT * FROM table1 left JOIN table2 ON table1.id = table2.numid where visualizza='1' ORDER BY id DESC";
I'm going to assume that you are trying to pull a ton of records. The best way to approach this is to add pagination and only load ~10-20 comments per page. depending on your server
Update:
#OP Basically on first load of the page you load ~10 comments, once they click view more then you load in the next few using ajax. Rinse and repeat.

how to count the total comment

I want to count the total comment/post posted on my page. i have a table in my database named test. within table i have a column named comment, where every post is been stored. the problem am having is to echo out the total number of comment and keep updating as viewers keep on posting there comment and i tried using this code
<?php
$handle = mysql_query("SELECT `comment`, COUNT(*) AS `count`
FROM test GROUP BY `comment` ");
if ($handle) {
$results = mysql_fetch_assoc($handle);
echo ($results[0]['count'] + $results[1]['count']);
}
?>
but it keep on echoing out 0. pls help me out.
Try this:
list($count) = mysql_fetch_row(mysql_query("select count(*) from `test`"));
echo $count;
Alternatively, if you are already running a query to get some comments, you can try this:
$sql = mysql_query("select sql_calc_found_rows * from `test` order by `id` desc limit 10");
// ^ Get the 10 most recent comments
list($count) = mysql_fetch_row(mysql_query("select found_rows()"));
// this avoids having to run the entire query again, great for efficiency!
while($comment = mysql_fetch_assoc($sql)) var_dump($comment); // just an example

Categories