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)
Related
I'm building a simple bug tracking tool.
When you create a new project, all the info you fill in in the form, gets stored in the database.
When you create the new project you get redirected to a unique project page.
On top of the page it shows the name of the project, but it's not the name of the project I just created, it always shows the name of the first project in the MySQL table.
How can I show the name of the project I just created?
With this query I retrieve the data from the database.
$query = "SELECT CONCAT(name)
AS name FROM projects";
$result = #mysql_query ($query)
With this I show the project name, but it always shows the name of the first record in the table.
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
It isn't yet SQL Injection prove and is far from complete... But I'm really struggling with this problem.
You need an AUTO_INCREMENT field on your table for a unique identifier (at least, you really should). Then you can do something like this:
<?php
$sql = new MySQLi('localhost', 'root', '', 'database');
$sql->query('INSERT INTO `projects` (`name`) VALUES ("Test Project");');
$projectID = $sql->insert_id; // Returns the auto_increment field value of the last insert query performed
// So this assumes you have a field in your table called "id" in this example
$res = $sql->query('SELECT CONCAT(`name`) AS `name` FROM `projects` WHERE `id` = '.$projectID.';');
if ($row = $res->fetch_assoc()) {
echo '<h5>'.$row['name'].'</h5>';
}
?>
Since you were calling for a redirect to the unique project page, you should have something like this: header("Location: project.php?id=$projectID");
Then, on project.php, you can attempt to fetch the project with the query above, only your query's WHERE clause should be something like:
'`id` = '.intval($_GET['id']).';'
Technically, you could pass all the project info along to the next page as a request or a session cookie and save yourself a query altogether. Just make sure you keep the id handy so it's easy to update the record.
Try using ORDER BY.
$query = "SELECT CONCAT(name)
AS name FROM projects ORDER BY id DESC";
This would show the most recent project (assuming you have an ID column).
However, a much better way is to have an ID variable on the page.
$query = "SELECT CONCAT(name)
AS name FROM projects WHERE id=?";
Hi I'm wondering if someone can help me please, I'm a new to MySQL.
I have a two tables:
Table One
div_attachments fields: ID Fkey Images Time
Table Two:
div_submissions fields: ID Name Phone Email
I'm using a php page in Joomla to display the data. I want to display the Images from div_attachments on the submissions page which uses the table div_submissions.
I think its something like:
SELECT * FROM $div_attachments AND $div_submissions
WHERE FKEY==ID
Can someone please help with the put together the query that I need to display the image in submissions?
Thanks.
Here is what I tried
$data = array();
foreach(explode(',',$item->attachments) as $value):
$db = JFactory::getDbo();
$query= $db->getQuery(true);
$query
>select('image')
>from('`#__div_attachments`')-
>where('fkey = ' .$value);
$db->setQuery($query);
$results = $db->loadObjectList();
if(count($results)){
$data[] = $results[0]->image;
}
endforeach;
echo implode(',',$data); ?>
"I want to display the Images from div_attachments on the submissions page which uses the table div_submissions."
Have you tried just selecting the image from div_attachments by id?
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.
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";
I'm currently using the following PHP code:
// Get all subordinates
$subords = array();
$supervisorID = $this->session->userdata('supervisor_id');
$result = $this->db->query(sprintf("SELECT * FROM users WHERE supervisor_id=%d AND id!=%d",$supervisorID, $supervisorID));
$user_list_query = 'user_id='.$supervisorID;
foreach($result->result() as $user){
$user_list_query .= ' OR user_id='.$user->id;
$subords[$user->id] = $user;
}
// Get Submissions
$submissionsResult = $this->db->query(sprintf("SELECT * FROM submissions WHERE %s", $user_list_query));
$submissions = array();
foreach($submissionsResult->result() as $submission){
$entriesResult = $this->db->query(sprintf("SELECT * FROM submittedentries WHERE timestamp=%d", $submission->timestamp));
$entries = array();
foreach($entriesResult->result() as $entries) $entries[] = $entry;
$submissions[] = array(
'user' => $subords[$submission->user_id],
'entries' => $entries
);
$entriesResult->free_result();
}
Basically I'm getting a list of users that are subordinates of a given supervisor_id (every user entry has a supervisor_id field), then grabbing entries belonging to any of those users.
I can't help but think there is a more elegant way of doing this, like SELECT FROM tablename where user->supervisor_id=2222
Is there something like this with PHP/MySQL?
Should probably learn relational databases properly sometime. :(
EDIT:
here is the relevant schema
submissions
===============================
id, user_id, timestamp
submittedentries
===============================
id, user_id, timestamp
users
===============================
id, supervisor_id, email
one submission has many submittedentries, and currently I'm referencing this by using the timestamp. I'd be more than willing to alter this if someone can suggest a more efficient way. (and yes, there are more fields that I'm omitting)
This should, if I got the column names correct, get a list of submissions from users who have the specified supervisor.
SELECT * FROM users, submissions
WHERE users.supervisor_id = $supervisorID
AND submissions.user_id = users.id
This version attempts to combine the timestamp checking as well.
SELECT * FROM users, submissions, submittedentries
WHERE users.supervisor_id = $supervisorID
AND submissions.user_id = users.id
AND submittedentries.timestamp = submissions.timestamp
Edit: Updated to match the additional table info. I'm still not 100% sure that the second version is correct, will need to be tested against the database to find out :)
Oh, and in practice you should probably replace the asterisk with the names of the actual columns you want to retrieve.