MySQL Display Image - php

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?

Related

Filter MySQLi with checkboxes

At the moment, I have a page that is displaying some posts. News posts, blog posts etc. What I want to achieve is having checkboxes so the user can check off, whatever kind of post he/she wants to see.
I should for instance be able to check off ´news´ and ´talking points´ and only see posts with those categories, and not see posts with the category ´blog´ for instance.
My current query looks like this (gets all posts, no matter the category). I believe some jQuery should be involved but I am not sure. How can I connect checkboxes with the query?
Can anyone help me with this?
$sql = "SELECT * FROM articles ORDER BY id DESC";
EDIT
I have tried this, but whenever I use the checkboxes, nothing is shown but I do not get an error?
My code:
<?php
if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['check_list'])){
$categories = $_POST['check_list'];
// Loop to store and display values of individual checked checkbox.
foreach($categories as $selected){
echo $selected."</br>";
}
}
}
?>
<br /><br />
<?php
if(!empty($_POST['check_list'])){
$sql = "SELECT * FROM articles ORDER BY id DESC WHERE `category` IN (".implode(',',$categories).")";
} else {
$sql = "SELECT * FROM articles ORDER BY id DESC";
}
Each checkbox should have a value. When you submit your form (probably a $_POST) you will see on the backend which checkboxes are checked. You can inspire from this tutorial: https://www.formget.com/php-checkbox/
IMPORTANT - You should filter the form data before using it in your SQL query. You can inspire from here: http://php.net/manual/en/function.filter-input.php
And you should prepare the variable before using it in the SQL Query:
$unsafe_variable = $_POST["user-input"];
$safe_variable = mysql_real_escape_string($unsafe_variable);
Now that you know which checkboxes are checked, you need to change the SQL query in order to filter by them.
So I suppose the checkboxes values are numbers (representing id's). So you will have an array called $ids that will contain all the checked checkboxes. Your mysql query will become something like:
$sql = "SELECT * FROM articles WHERE `id_category` IN (".implode(',',$ids).") ORDER BY id DESC";

How to display average values from MySQL table

I have a MySQL database that holds details on various video games and user accounts. A user is able to review a game and the score is put into a review table.
I am trying to retrieve the average score for each game and have it displayed on a webpage. My SQL statement within PHP looks like this
$sqlOverall = "SELECT CAST(AVG('scoreOverall') AS DECIMAL('10,1'))
FROM 'ratings'
WHERE gameID = '$id'";
$scoreOverall = mysqli_query($conn, $sqlOverall);
But when I try to echo $scoreOverall it returns blank.
SELECT CAST(AVG(scoreOverall) AS DECIMAL(10,1))
FROM ratings
WHERE gameID = '$id';
Try above code.
Hope this will helps.
try this below query
$selquery="SELECT CAST(AVG(scoreOverall) AS DECIMAL(10,1)) FROM ratings WHERE gameID='$id'";
$result= mysqli_query($conn, $selquery);
It works fine. Hope it is your helpful
$sqlOverall="SELECT CAST(AVG(scoreOverall) AS DECIMAL(10,1)) FROM ratings WHERE gameID=$id";
$scoreOverall = mysqli_query($conn, $sqlOverall);
foreach ($scoreOverall as $value) {
$scoreOverall = $value['CAST(AVG(queue_status) AS DECIMAL(10,1))'];
echo $scoreOverall;
}

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

Show data from a specific row in MySQL

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=?";

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