Building a dynamic HTML list from MySQL results - php

I have a set of tables (for this question I'll say two) in the database, one of which is the users table and one of which is one for storing URL's. The one that store URL's contains the URL ID (auto increment) and the User_ID. The user id is submitted when the add url form is submitted.
I'm trying to figure out how I can display these results as a table. For each user I need to get the list of URL's that are associated with their account and display them as a list. I have the user-id stored as a variable so it can be called from anywhere. How would I select items from the database that are only associated with the current logged in users id? and also how would I then generate a list of the results.
Thanks in advance.

This is a very basic php mysql question so you can probably find it by looking around the site but to save you some time:
//assuming the userid for logged in user is in $userid
$sql = "SELECT * FROM urls_table WHERE User_ID=$userid";
$result = mysql_query($sql); $data = array();
while($row=mysql_fetch_assoc($result)) {
$data[] = $row['URL'];
}
print_r($data);
//or foreach($data as $url) print "$url\n";
If instead of the user id of the logged in user you had the name then do an inner join like so:
//assuming the user name for logged in user is in $username
$sql = "SELECT * FROM urls_table INNER JOIN users_table ON urls_table.User_ID = users_table.User_ID WHERE User_Name=$username";
$result = mysql_query($sql); $data = array();
while($row=mysql_fetch_assoc($result)) {
$data[] = $row['URL'];
}
print_r($data);
//or foreach($data as $url) print "$url\n";

Related

create json array from multiple mysql query

for example i have two tables post table and user table, and from these i want to create a json array to pass bootstrap datatable.
My table structure. post table and user table. i want to generate an output table having post details and user details.but user name should be in drop down box.
<?php
include('config/db_i.php');
$sql_post = mysqli_query($con,"SELECT * FROM `post_tbl`");
$array = array();
$array['data'] = array();
while($res_post = mysqli_fetch_array($sql_post)){
$sql_user = mysqli_query($con,"select * from user_tbl where user_id='".$res_post['user_id']."'");
$row_user = mysqli_fetch_array($sql_user);
//what i'll code here
$array['data'][] = $res_post;
}
echo json_encode($array);
?>
You can do the concatenation at query level by joining the two tables together as such :
Select ps.post_id, ps.post_title, us.user_id, us.user_name FROM post_tbl AS ps JOIN user_tbl AS us ON ps.user_id = us.user_id
That way each row of the fetched array will have the post info and the user info which you can freely pass to bootstrap datatable.
*You can also use NATURAL JOIN

PHP get variable from on table and then use that variable to select from a second table

I'm building a followers list for a user. I have two tables the first shows the relationships between users and the second table holds every users profile info. In the following code, I first select from the user relationships table to get a variable {$userid1} which is the value of all the user ids that follow the current user. When I echo out {$userid1} I get all the ids of the users who follow the current user but it is one giant connected string. I want to take the variable {$userid1} and use it to pull every one of those follower's user data from the profile table. I want every user's data to show up from the profile table that follows the current user. The code works however only the newest follower's profile data is pulled from the profile table. I was thinking putting the variable {$userid1} into an array and using foreach, but I'm not sure how the syntax would be. Anybody know how it could work? The problem is a variable can only hold one value at a time.
Output of the first query are the iduser numbers from the users following the current user.
e.g. when echoed echo $userid1 . " "; the results are the ids look like this: 45 56 67
I added a space between numbers in the echo statement.
$sql = mysql_query("SELECT * FROM followrelations Where iduser2='$uid' "); //followers from relations table
while($row = mysql_fetch_array($sql)){
$userid1 = $row['iduser1'];
echo $userid1 . " ";
}
$sql = mysql_query("SELECT * FROM profile where iduser=$userid1 ORDER BY username ");//get followers infor from profile using variable
while($row = mysql_fetch_array($sql)){
$iduserf = $row['iduser']; //userid2 requires different var name so program does not get mixed up
$username = $row['username'];
$bio = $row['bio'];
$avatar = $row['avatar'];
echo "
<div style='width:500px;height:100px;padding:20px 20px;float:left;border: solid black 1px;'>
<a href='profile.php?uid=$iduserf'><img src=$avatar height=50px width=50px /></a></br>
<a href='profile.php?uid=$iduserf'>$username </a></br>
</div>" ;
}
You might be looking for subqueries:
SELECT username
FROM user_table
WHERE id IN( SELECT user_id WHERE linked_user_id = 123 )
This is simplefied to be a better example. This will select the username of all users from the user_table, where the ID exist in the subquery.
In turn, the subquery selects all user_id where the linked user has id=123.
The subquery is quite similar to making an array in PHP and use that info for the next query.
Small note: Be carefull with subqueries. They're perfect in my example above, but eg not all servers support a limit in the subquery. This might effect performance. The more complecated functions don't work in a subquery. Try to keep those simple.
You can use something like the following to execute this in a single query:
$id = mysql_real_escape_string($uid);
$sql = <<<SQL
SELECT
p.*
FROM profile as p
INNER JOIN followrelations as fl
ON fl.iduser1 = p.userid
WHERE fl.iduser2 = $id
ORDER BY username
SQL;
$stmt = mysql_query($sql);
while($row = mysql_fetch_array($stmt)){
// Rest of the logic here
}
This will return all the fields in your profile table. Note that the mysql_ extension is deprecated and unsafe - you should not be using it in new code. Take a look at How to replace MySQL functions with PDO? and How can I prevent SQL injection in PHP? for some good practices regarding this.
Found my mistake, the second $sql should be another name (I named it $sql1), and the second half should all be within the first while.
$sql = mysql_query("SELECT * FROM followrelations Where iduser2='$uid' "); //followers session uid
while($row = mysql_fetch_array($sql)){
$userid1 = $row['iduser1'];
$sql1 = mysql_query("SELECT * FROM profile where iduser='$userid1' ORDER BY username ");//get followers infor from profile using variable
while($row = mysql_fetch_array($sql1)){
$iduserf = $row['iduser']; //userid2 requires different var name so program does not get mixed up
$username = $row['username'];
$bio = $row['bio'];
$avatar = $row['avatar'];
echo "
<div style='width:500px;height:100px;padding:20px 20px;float:left;border: solid black 1px;'>
<a href='profile.php?uid=$iduserf'><img src=$avatar height=50px width=50px /></a></br>
<a href='profile.php?uid=$iduserf'>$username </a></br>
</div>" ;
}
}

how to create link depending on user input

This is the code for the user to post the post.
if(islet($_POST['submit'])) {
$name = $_POST['name'];
$keywords = $_POST['keywords'];
$description = $_POST['description'];
if(islet($_GET['user_id'])) {
$_SESSION['user_id'] = $_GET['user_id'];
} //Then I just have a inset into statement for my database with these 4 variables.
}
I have a web form that creates a post by the user. I now want to make the user able to go back to a page dedicated to that post for them to edit, add on to etc.
Here is the high level solution:
You need to create a page that expects a post_id as a parameter of the query string. That page will be accessed like this: http://yoursite.com/show-post.php?post_id=136
In PHP, retrieve that post_id: $_GET['post_id']
From that post id, pull from the DB the information associated to that id. Something like SELECT * FROM post WHERE post_id = $_GET['post_id'].
Then display the post using the information returned by the SQL query.
If you want to show a list of posts from the current user, create another page http://yoursite.com/my-posts.php.
From that page, write a SQL query based on the current user id: SELECT * FROM post WHERE user_id = $_SESSION['user_id'] (assuming you have a user_id in the post table, and the user has authenticated and his id was stored in the session).
That will fetch you a list of posts, loop through them to get their details.
Please note that you should escape the parameter passed in the query string. There are many ways to do this so I won't go into it here.
EDIT:
This is how you generate the links:
<?php foreach ($mysql_result as $row) { ?>
link
<?php } ?>
Then, in edit-post.php, you can get the post_id by doing $postId = $_GET['post_id'];, and then use it in the query to fetch ALL the information about that one particular post.
Make sure you have a unique ID column in your database - call it 'postid', and set it to autoincrement with every new entry.
That way you'll be sure to have a unique identifier for each entry you insert in to the database.
You then need to retrieve a list of items in the database, including the postid, and for each row in the database provide a link to display it.
If a postid is selected in the url, then display information for that post. If it isn't, then show a list:
<?
$dbh = new PDO('mysql:host=localhost;dbname=databasename;charset=utf8', 'username', 'password');
///No post id selected, display a list of everything
if(!$_GET['postid']) {
print "You're listing all the rows in the database<br/>";
$query = $dbh->prepare("SELECT `postid`,`name` FROM `table` ORDER by postid ASC");
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
print "".$row['name']."<br/>";
}
} else { //A post ID is selected
$postid = $_GET['postid'];
Print "Select from the database where postid = ".$postid;
$query = $dbh->prepare("SELECT `postid`, `name`, `keywords`, `description` FROM `table` WHERE `postid` = '$postid' LIMIT 1");
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$name = $row['name'];
$keywords = $row['keywords'];
$description = $row['description'];
print 'Displaying details for '.$name.': '.$keywords.', '.$description.' - create edit links here... <br/><br/>';
}
} //End post id is selected
?>

Sorting the results of a mysql query

Im having difficulties trying to figure out an elegant solution to sorting the results of a mysql query based on a delimited string. Ill explain in more detail below
I am creating a database of contacts where individual users can add/remove people from a list. When the user adds a new contact I append the added contact id to a delimited string and store that data in a database column associated with that user (named contacts):
$userID = ?? //YOUR ID
$contactID = ?? //WHATEVER THE ADDED USER ID IS
$confirm = 0 //has the user been confirmed
$sql = "SELECT contacts FROM user WHERE id = '$userID'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
$contact = $row['contacts'];
$contact .= '|'.$contactID.':'.$confirm;
$update = mysql_query("UPDATE user SET contacts = '$contact' WHERE id = '$userID'");
//contact column data might be: |10:0|18:0|36:0|5:0
When the user searches their contacts I grab the data from the contacts column, explode/split the string and return the individual users names:
$userID = ?? //YOUR ID
$sql = "SELECT contacts FROM user WHERE id = '$userID'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
$contacts = explode("|", $row['contacts']);
foreach($contacts as $item)
{
list($contactID,$confirm) = split(":", $item);
$sql = "SELECT name FROM ".user." WHERE id = '$contactID'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
echo($row['name'].'<BR>');
}
This indeed does return all the names, but it returns them in the order of the delimited string. I cant seem to find an elegant way to sort by name alphabetically.
Should I not store the contacts list in a delimited string? How would you solve this?
You're right, you should not store the contacts in a string. Instead use another table which contains the user information. The new table should look something like the following:
Table: user_contacts
| user_id | contact_id | confirm |
-------------------------------------------
| your data here... |
Then when you need your contact list you can simply perform another query:
SELECT * FROM `user_contacts`
JOIN `users` ON `users`.`id` = `user_contatcs`.`user_id`
WHERE `users`.`id` = $id
ORDER BY `users`.`name`;
Or however you need to order it.
There are two obvious approaches:
Sort the results once you've fetched them
Fetch them all in one query and have the DB sort them
For #1, use usort():
$rows = array();
foreach ($contacts as $item){
list($contactID,$confirm) = split(":", $item);
$query = mysql_query("SELECT name FROM user WHERE id = '$contactID'");
$rows[] = mysql_fetch_array($query);
}
usort($rows, 'sort_by_name');
function sort_by_name($a, $b){
return strcmp($a['name'], $b['name']);
}
foreach ($rows as $row){
echo($row['name'].'<BR>');
}
For #2, build a list of IDs and use IN:
$ids = array();
foreach ($contacts as $item){
list($contactID,$confirm) = split(":", $item);
$ids[] = $contactID;
}
$ids = implode(',', $ids);
$query = mysql_query("SELECT name FROM user WHERE id IN ($ids) ORDER BY name ASC");
while ($row = mysql_fetch_array($query)){
echo($row['name'].'<BR>');
}
If you're using a relational database, then what you want is a separate table that stores person-contact relationships. Then you would modify your sql query to select based on a join across two tables
SELECT * FROM person, contact
JOIN contact ON person.id = contact.personid
JOIN person ON contact.contactid = person.id
WHERE person.id = $id
ORDER BY person.lastname
(That code is probably not quite correct.)
If you're using a no-sql type implementation, the way you're doing it is fine, except that you will either have to programmatically sort after the fact, or sort-on-insert. Sort on insert means you'd have to query the current list of contacts on inserting one, then sort through to find the right position and insert the id into the delimited string. Then save that back to the db. The downside to this is you'll only be able to sort one way.
Generally, people use relational databases and 'normalize' them as described above.

Export/Import Table Function

I'm using Joomla 1.7 and I've got a little problem and was wondering if anyone could help. I have a component installed on my site that users can use to create playlists. These are stored in a table that contains fields for name, user id, playlist id, playlist name, and songs. The songs each have a unique id and a playlist is held in a field like so: 7,2,4,68,70.
What id like to do is create a an import/export feature. I figured the easiest thing for exporting would be to export a users playlist table as a sql file. Then for importing an sql file would have its fields read and new playlist table would be created using only the song field and name field. The user id field would be filled in with the current user and the playlist id field checked against existing playlist ids and a new one assigned.
Right now I know that current playlist creation is being managed by the component in components/com_muscol/models.php
I started trying to create the function but I am a little lost on how to export the data as an sql file:
function get_mysql(){
$db =& JFactory::getDBO();
$query = 'SELECT pl.*, us.name AS username FROM #__muscol_playlists AS pl LEFT JOIN #__users AS us ON us.id = pl.user_id WHERE pl.id = ' . $this->_id ;
$this->_db->setQuery( $query );
}
Thanks for your help...
To export your data as SQL, just loop through it. Something like this should work:
$sql = array();
$query = mysql_query("YOUR QUERY HERE");
while($result = mysql_fetch_assoc($query){
$cols = array('user_id'); // put ID's etc. into $cols and $vals
$vals = array($user_id);
foreach($result as $col => $val){
$cols[] = $col;
$vals[] = $val;
}
$sql[] = "INSERT INTO `#__muscol_playlists` (`".implode('`,`', $vals)."`) VALUES('".implode('`,`', $cols)."')";
}
echo explode("\n", $sql);
(note: This was written on the spot as an example and hasn't been tested at all, so don't expect it to magically work if you just copy paste it)

Categories