I've asked this question before, but got no answers, so I'm asking it again but this time, I will be more specific.
I have an online forum which I created from scratch with php and mysql, I've implemented the image uploading part naming the image by the topic id, from the posts table, Now I'm having problems displaying the images by pulling the name and the extension from the image table and attaching it to the topic id to be displayed. Now this is the code snippet for displaying topics (viewtopic.php)
$sql = "
SELECT SQL_CALC_FOUND_ROWS p.id
, p.subject
, p.body
, p.date_posted
, p.date_updated
, u.name as author
, u.id as author_id
, u.signature as sig
, c.count as postcount
, p.forum_id as forum_id
, f.forum_moderator as 'mod'
, p.update_id
, u2.name as updated_by
FROM forum_forum f
JOIN forum_posts p
ON f.id = p.forum_id
JOIN forum_users u
ON u.id = p.author_id
LEFT
JOIN forum_users u2
ON u2.id = p.update_id
LEFT
JOIN forum_postcount c
ON u.id = c.user_id
WHERE $topicid IN (p.topic_id,p.id)
ORDER
BY p.topic_id
, p.date_posted
LIMIT $start,$limit;
";
$result = mysqli_query($sql, $conn)
or die(mysql_error() . "<br>" . $sql);
while ($row = mysqli_fecth_array($result) )
{
echo "<p>($body) . "</p>";
echo $sig;
}
Now after echo ($body) if I run this query;
$sql = "SELECT * FROM images WHERE name = '$name'";
$result = mysqli_query($sql) or die('Could not SELECT image data ' . mysql_error());
while ($therow = mysql_fetch_array($result))
{
$image_name = $therow["name"] ;
$ext = $therow["extension"];
}
?>
<img src="images/<?php echo $image_name.$ext; ?>" >
Help me, how do i get images to be displayed?
Try replace this:
while ($row = mysqli_fecth_array($result) )
{
echo "<p>($body) . "</p>";
echo $sig;
}
to
while ($row = mysqli_fetch_array($result) )
{
echo "<p>($body)" . "</p>";
echo $sig;
}
and this
$sql = "SELECT * FROM images WHERE name = '$name'";
$result = mysqli_query($sql) or die('Could not SELECT image data ' . mysql_error());
while ($therow = mysql_fetch_array($result))
{
$image_name = $therow["name"] ;
$ext = $therow["extension"];
}
?>
to
$sql = "SELECT * FROM images WHERE name = '$name'";
$result = mysqli_query($sql) or die('Could not SELECT image data ' . mysql_error());
while ($therow = mysqli_fetch_array($result))
{
$image_name = $therow["name"];
$ext = $therow["extension"];
}
?>
Related
for the past few hours, I have been trying to find a simple method of while loop echoing information from multiple tables at once. I'd like to say I've not pulled all my hair out looking, but I have.
Here is one mysqli query to get the following fields from CUSTOMER
$tid = $_SESSION['user_id']; // "id" is 1 for example
$query = "SELECT * FROM `CUSTOMER` WHERE user_id = {$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['user_id'] . "<br><br>";
echo $row['c_fname'] . "<br>";
echo $row['c_sname'] . "<br>";
};
Here is another mysqli query to get the following fields from SALE
$query = "SELECT * FROM `SALE` WHERE user_id = {$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['s_date'] . "<br>";
echo $row['s_total'] . "<br>";
};
Could someone possibly show me how I can get both of these tables in one query so that echoing both tables information is possible at the same time instead of separately. I am not fussed how it is done, As long as it gets all from both tables for echoing purpose, that is good.
You can do it by using LEFT JOIN like this.
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
And this is your code.
$query = "SELECT * FROM `CUSTOMER` LEFT JOIN `SALE` ON `SALE`.user_id=`CUSTOMER`.user_id WHERE `SALE`.user_id={$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['user_id'] . "<br><br>";
echo $row['c_fname'] . "<br>";
echo $row['c_sname'] . "<br>";
echo $row['s_date'] . "<br>";
echo $row['s_total'] . "<br>";
}
For more info read this,
https://www.w3schools.com/sql/sql_join_left.asp
I hope this helps.
EDITED
This is for joining 3 tables,
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
LEFT JOIN table3 ON table1.column_name = table3.column_name;
In your code.
SELECT * FROM `CUSTOMER`
LEFT JOIN `SALE` ON `CUSTOMER`.user_id = `SALE`.user_id
LEFT JOIN `PRODUCTS` ON `CUSTOMER`.user_id = `PRODUCTS`.user_id
WHERE `SALE`.user_id={$tid};
As variable.
$query = "SELECT * FROM `CUSTOMER` LEFT JOIN `SALE` ON `CUSTOMER`.user_id = `SALE`.user_id LEFT JOIN `PRODUCTS` ON `CUSTOMER`.user_id = `PRODUCTS`.user_id WHERE `SALE`.user_id={$tid}";
You can use the following code and will help u solve Ur problem
$query = "SELECT C.*,S.* FROM CUSTOMER C,SALES S
WHERE C.user_id={$tid}
and C.user_id=S.user_id;
while ($row = mysqli_fetch_array($results)) {
echo $row['C.user_id'] . "<br><br>";
echo $row['C.c_fname'] . "<br>";
echo $row['C.c_sname'] . "<br>";
echo $row['S.s_date'] . "<br>";
echo $row['S.s_total'] . "<br>";
};
You can simply join the tables to get your expected result as shown below.
$query = "SELECT c.user_id, c.c_fname, c.c_sname, s.s_date, s.s_total FROM `CUSTOMER` AS c INNER JOIN `SALE` AS s ON c.user_id = s.user_id WHERE c.user_id = {$tid}";
Joining 3 tables example
$query = "SELECT *
FROM `CUSTOMER` AS c
INNER JOIN `SALE` AS s ON c.user_id = s.user_id
INNER JOIN `PRODUCTS` AS p ON p.product_id = s.product_id
WHERE c.user_id = {$tid}";
I have 3 tables:
Table: album
Columns: id, name, description, author, path, image
Table: albumconnect
Columns: id, imageid, albumid
Table: albumimages
Columns: id, path
And I'm trying to replace all those unnecessary queries with a single JOIN query:
<?php
$albumID = $_SERVER['QUERY_STRING'];
$realAlbumID = substr($albumID, 1);
$realestAlbumID = str_replace('%20', ' ', $realAlbumID);
$sql = "SELECT * FROM album WHERE id='$realestAlbumID'";
$result = mysqli_query($conn, $sql);
$getResult = mysqli_fetch_assoc($result);
$albumPath = $getResult['path'];
$sql2 = "SELECT * FROM albumconnect WHERE albumid='$realestAlbumID'";
$result2 = mysqli_query($conn, $sql2);
while ($row = $result2->fetch_assoc()){
$imageId = $row['imageid'];
$sql3 = "SELECT * FROM albumimages WHERE id='$imageId'";
$result3 = mysqli_query($conn, $sql3);
$getResult3 = mysqli_fetch_assoc($result3);
$imagePath = $getResult3['path'];
echo '<div class="imageContainerAlbums"><li class="listAlbums"><img class="specificAlbumThumnails" src="'.$albumPath.$imagePath.'" alt="Random image" /></li></div>';
};
?>
Now the JOIN query I've come up with based on stuff I've read online is this:
$sql5 = "SELECT * FROM album
JOIN albumconnect ON albumconnect.albumid=album.id
JOIN albumimages ON albumimages.id=albumconnect.imageid
WHERE id='$realestAlbumID'";
$result5 = mysqli_query($conn, $sql5);
However, when I try to var_dump the contents, it prints Null so I assume my query is incorrect but I can't figure out the correct way to do it.
Should be something like this. I didn't test it. As #Difster correctly said, SQL engine doesn't know which id should it reference. So, define table aliases and prefix the referenced columns with them. Then define unique aliases for the column names too. Otherwise your sql statement were almost perfect.
<?php
$albumID = $_SERVER['QUERY_STRING'];
$realAlbumID = substr($albumID, 1);
$realestAlbumID = str_replace('%20', ' ', $realAlbumID);
$sql = "SELECT
alb.name AS album_name,
alb.description AS album_description,
alb.author AS album_author,
alb.path AS album_path,
alb.image AS album_image,
ali.path AS image_path
FROM album AS alb
LEFT JOIN albumconnect AS alc ON alc.albumid = alb.id
LEFT JOIN albumimages AS ali ON ali.id = alc.imageid
WHERE alb.id = '$realestAlbumID'";
$result = mysqli_query($conn, $sql);
while ($row = $result->fetch_assoc()) {
$albumPath = $row['album_path'];
$imagePath = $row['image_path'];
echo '<div class="imageContainerAlbums">';
echo '<li class="listAlbums">';
echo '<img class="specificAlbumThumnails" src="' . $albumPath . $imagePath . '" alt="Random image" />';
echo '</li>';
echo '</div>';
}
EDIT 1:
The columns from the sql statement which you don't use later are optional. So, you don't need to select all columns if you don't need them later.
It maybe that you are also becoming rows with NULL values for alc or ali tables. It means that not all albums have images. Then you must give us values you have in the tables, so that we can provide you the proper further WHERE conditions like WHERE ali IS NOT NULL. This answer of me is just the starting point for you.
EDIT 2:
This version is ok too. I just changed the sql statement.
<?php
$albumID = $_SERVER['QUERY_STRING'];
$realAlbumID = substr($albumID, 1);
$realestAlbumID = str_replace('%20', ' ', $realAlbumID);
$sql = "SELECT
alb.name AS album_name,
alb.description AS album_description,
alb.author AS album_author,
alb.path AS album_path,
alb.image AS album_image,
ali.path AS image_path
FROM albumimages AS ali
LEFT JOIN albumconnect AS alc ON alc.imageid = ali.id
LEFT JOIN album AS alb ON alb.id = alc.albumid
WHERE alb.id = '$realestAlbumID'";
$result = mysqli_query($conn, $sql);
while ($row = $result->fetch_assoc()) {
$albumPath = $row['album_path'];
$imagePath = $row['image_path'];
echo '<div class="imageContainerAlbums">';
echo '<li class="listAlbums">';
echo '<img class="specificAlbumThumnails" src="' . $albumPath . $imagePath . '" alt="Random image" />';
echo '</li>';
echo '</div>';
}
I have a php code that use a mySQL query in it.
tables users and conversation and main_profile have true values to select after this query but query return nothing.
$sqlQuer =
"SELECT `conversation`.from,`conversation`.text, `main_profile`.nik_name, `users`.id
FROM `conversation`
INNER JOIN `users` ON(`users`.username = `conversation`.to )
INNER JOIN `main_profile` ON(`users`.id = `main_profile`.user_id)
WHERE `conversation`.to = '".$to."'
AND `conversation`.read = '0'";
$result = mysql_query( $sqlQuer) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row[0] . "#TEXT#" . $row[1]. "#TEXT#" . $row[2] . "#CON#";
$ids[] = $row['id'];
}
any Idea ?
Query was solved with this change that First INNER JOIN changed to LEFT JOIN and second changed to RIGHT JOIN.
<?php
function get_user_id($username) {
return mysql_result(mysql_query("Select id From users Where username = '" . mysql_real_escape_string($username) . "'"), 0);
}
$sql = "select * from rating
WHERE user_id=" . get_user_id($myusername) . "
ORDER BY punkte ASC";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$catid = $row['rating_id'];
$catname = $row['song_id'];
echo "<li id='item_$catid' class='ui-state-default'><span class='ui-icon ui-icon-arrowthick-2-n-s'></span>$catname</li>";
}
?>
UPDATE:
Sorry, I found the mistake, it was quite stupid:
$catid = $row['rating_id'];
$catname = $row['song_id'];
It should be:
$catid = $row['song_id'];
$catname = $row['song_name'];
So, thanks to all! As always: You can't figure it out before you post a question to Stackoverflow :)
For your new question, you can solve it with a inner join:
select s.song_name from rating r
inner join songs s on s.song_name_id = r.song_id
Inner join
http://www.w3schools.com/sql/sql_join_inner.asp
Yes,
$catid = $row['rating_id']; //rating id is not related to song
TO
$catid = $row['song_id'];
$catname = $row['song_name'];
So i'm not that experienced in programming, and am working on some php.
My queries (not counting my broken if-else statements >_>), but when I submit 1 query (query2 for example), that works, it prints the results, as well as the results of another query7. How can I stop that?
Also if anyone has any clue where I failed in my if-else statements for the first query and query6, I'd appreciate some insight (they all use html submit buttons)
Thanks!
Here's my problem php code:
$lastName = $_POST['lastName'];
if ($_Post['lastName'] = "") {
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE s.Contact_con_id = c.con_id ";
} Else {
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE s.Contact_con_id = c.con_id
AND con_lname = ";
}
$query = $query . "'" . $lastName . "' ORDER BY con_lname;";
$rgroups = $_POST['rgroups'];
if ($_Post['rgroups'] = "") {
$query6 = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = ";
$query6 = $query6 . "'" . $rgroups . "' Group BY r.rev_groups_id;";}
Else {
$query6 = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = ";
$query6 = $query6 . "'" . $rgroups . "' ";}
$check = $_POST['check'];
$query7 = "Select c.con_fname, c.con_lname, s.Contact_con_id,
IF(s.Contact_con_id IS NULL, 'NO', 'YES')
From Contact c Left Join (Select Contact_con_id FROM Speakers
WHERE speaker_year = '". $check . "') As s
ON c.con_id = s.Contact_con_id";
$query7 = $query7 . " ORDER BY c.con_fname;";
(this is the code that prints on every result)
$average = $_POST['average'];
$query5 = "SELECT c.con_fname, r.Reviewer_Contact_con_id, question_id, AVG( DISTINCT question_score)
FROM Contact c, Individual_Review r
WHERE r.Reviewer_Contact_con_id = c.con_id
AND con_fname = ";
$query5 = $query5 . "'" . $average . "' GROUP BY r.Proposal_proposal_id;";
(example of working code. you can put in George next to con_fname to get a result)
// 1. Format your code with indents, etc.
// 2. Comment your code
// 3. Don't pass $_POST data straight to your sql.
// 4. Variables are case sensitive, including POST
$lastName = $_POST['lastName'];
if ($lastName = "") {
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE
s.Contact_con_id = c.con_id ";
}else{
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE
s.Contact_con_id = c.con_id
AND con_lname = ";
}
$query = $query . "'" . $lastName . "' ORDER BY con_lname;";
// if you did the first if, then this broke.
// Use:
// echo $query;
// to see what you have so far.
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE
s.Contact_con_id = c.con_id
AND con_lname = '".$lastName."' ORDER BY con_lname";
$rgroups = $_POST['rgroups'];
// you can go like $query .=
// you don't have to do $query = $query;
// so all of this could be:
$query6 = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local' ";
if ($_Post['rgroups'] = "") {
$query6 .= " AND r.rev_groups_id = '" . $rgroups . "' Group BY r.rev_groups_id;";
}else{
$query6 = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = '" . $rgroups . "' ";
}
$check = $_POST['check'];
You could add your $query7 in some if condition to avoid that
Note: I am dealing only with your PHP structure. I haven't looked at your SQL syntax at all. But I gave you the tools to see if SQL is returning what you think it should be returning.
<?PHP
// here are some functions for ya
function sqlarr($sql, $numass=MYSQL_BOTH) {
// MYSQL_NUM MYSQL_ASSOC MYSQL_BOTH
$got = array();
$result=mysql_query($sql) or die("$sql: " . mysql_error());
if(mysql_num_rows($result) == 0)
return $got;
mysql_data_seek($result, 0);
while ($row = mysql_fetch_array($result, $numass)) {
array_push($got, $row);
}
return $got;
}
// Sql fetch assoc
function sqlassoc($sql){
$query = mysql_query($sql) or die("$sql:". mysql_error());
$row = mysql_fetch_assoc($query);
return $row;
}
function sqlrow($sql){
$query = mysql_query($sql) or die("$sql:". mysql_error());
$row = mysql_fetch_row($query);
return $row;
}
function sqlquery($sql){
$query = mysql_query($sql) or die("$sql:". mysql_error());
return $row;
}
function printr( array $array, $label = '' ){
echo '<pre>'.$label;
print_r( $array );
echo '</pre>';
}
// This isn't the best, but it's better than nothing
// use PDO when you get more advanced
function makeSomewhatSafe($str){
return htmlspecialchars(stripslashes(strip_tags($str, '<p>')), ENT_QUOTES);
}
// good practice: initiate any variables you use at the beginning
// we're going to go ahead and strip them here too to try to avoid sql injection
$rgroups = makeSomewhatSafe($_POST['rgroups'] );
$lastName = makeSomewhatSafe( $_POST['lastName'] );
$query = NULL;
$speakerContactResulst = array();
$check = makeSomewhatSafe( $_POST['check'] );
$average = makeSomewhatSafe($_POST['average']);
// if($_Post['lastName'] = "") {
// we're going to see if it has a value
// another way to do this if your empty isn't working is to do
// if( strlen( $lastName ) > 0 ){
if( empty( $lastName ) ){
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE s.Contact_con_id = c.con_id ";
}else{
$query = "SELECT c.*, s.speaker_year FROM Contact c, Speakers s WHERE s.Contact_con_id = c.con_id
AND con_lname = ";
}
$query .= "'" . $lastName . "' ORDER BY con_lname";
echo 'This query states: '.$query.' <br /><br />';
$speakerContactResulst = sqlarr( $query );
printr( $speakerContactResulst, 'speakerContactResulst ');
if ( ! empty( $rgroups ) ){
$query = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = '" . $rgroups . "' Group BY r.rev_groups_id;";
}else{
// I dont know if you matters, but keep your else's more compact. Don't do like you had with the else on a new line
// str'; }
// else {
$query = "SELECT r.rev_groups_id, c.con_fname, c.con_lname, con_phone, rev_groups_pass, count(p.proposal_id)
FROM Review_Groups r JOIN Proposal p on r.rev_groups_id = p.Review_Groups_rev_groups_id
JOIN Presents px on px.Proposal_proposal_id = p.proposal_id
JOIN Contact c on px.Speakers_Contact_con_id = c.con_id
JOIN Reviewer rw on rw.Review_Groups_rev_groups_id = r.rev_groups_id
WHERE rw.reviewer_type = 'local'
AND r.rev_groups_id = '" . $rgroups . "' ";
}
$groupResults = sqlarr( $query );
printr( $groupResults, 'groupResults' );
$query = "Select c.con_fname, c.con_lname, s.Contact_con_id,
IF(s.Contact_con_id IS NULL, 'NO', 'YES')
From Contact c Left Join (Select Contact_con_id FROM Speakers
WHERE speaker_year = '". $check . "') As s
ON c.con_id = s.Contact_con_id ORDER BY c.con_fname;";
$checkResults = sqlarr( $query );
$query = "SELECT c.con_fname, r.Reviewer_Contact_con_id, question_id, AVG( DISTINCT question_score)
FROM Contact c, Individual_Review r
WHERE r.Reviewer_Contact_con_id = c.con_id
AND con_fname = '" . $average . "' GROUP BY r.Proposal_proposal_id;";
$averageResults = sqlarr( $query );
?>