Ok, so. I have asked about 5 questions on stackOverflow today, you've all been so helpful.
Now, i'm a designer, learning to code, so bear with me.
I have a mySQL table, with a small CMS/Blog im building.
I have it styled how I want to now.
This is the code for the page.
$result = mysql_query("SELECT * FROM Blog");
while($row = mysql_fetch_array($result))
{
echo "<h1>" . $row['Title'] . "</h1>";
echo "<br>";
echo "<h2>" . "Posted on: " . $row['Date'] . "</h2>";
echo "<br>";
echo "<img src='".$row['Image']."'/>";
echo "<br>";
echo $row['Message'];
echo "<br>";
echo "<br>";
}
I'm still working on it so its all good.
What I want to know is, this code is outputting my sql data into a page. Is there any way of telling the page what order to echo the data, for instance. in my SQL table i have:
2012-11-03 16:16:06 This is my First Blog Post This is the first message of the first blog post. ... http://blog.gettyimages.com/wp-content/uploads/201.
and next is
2012-11-03 16:17:29 This is my Second Blog Post This is the second message of the Second Post, You... http://www.aviation-images.com/user/zooms/118/451n...
How can i tell the page to Always display the most recent post at the top, and older ones below.?
Use order by in your query:
$result = mysql_query("SELECT * FROM Blog ORDER BY Date DESC");
If your MySQL database schema uses DATETIME for the Date column, you can simply sort in the MySQL query with ORDER BY:
$result = mysql_query("SELECT * FROM Blog ORDER BY Date DESC");
If you have an auto-increment column like post_id, then you can use ORDER BY post_id DESC as well. :)
Related
I'm trying to create a simple e-commerce system. First thing I did was select the rows with the same Order ID from mysql. My table looks like this:
Now, I'd like to know how I can group them into separate divs, it should look like this:
Here's my code:
$con = mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result2 = mysqli_query($con, "SELECT DISTINCT request_date, department_id FROM tbl_requests WHERE request_id=".$_GET['request_id']) ;
while($row2 = mysqli_fetch_array($result2)) {
echo "" . $row2['request_date'] . "<br/>";
echo "Order from Department " . $row2['department_id'] . "<br/>";
echo "<br/>";
echo "<hr/>";
echo "<br/>";
}
$result = mysqli_query($con,"SELECT * FROM tbl_requests WHERE request_id=".$_GET['request_id']);
while($row = mysqli_fetch_array($result)) {
echo "" . $row['request_details'] . "";
echo "<br/>";
}
I'm sorry if ever this question is incomplete, please feel free to ask me any more questions. Thank you in advance :)
You can check for every product in array using Javascript or jQuery(much easier).
This way you can check if your page does contain any existing div with that manufacture id (ie. #m_1055, #m_1040) or not.
If div does exist, append product in that div (in jQuery.append())
If not, then first append the div with that manufacture id to the document and then append the product to it.
I know the basics of MySQL and PHP. I've set up a posting system that echoes the fields from my table.
The only problem is, since this is a news page, the newest posts need to be on top. And when the page echoes back the results, it puts the first entry I made (in the table) at the top.
This is my code:
// Selecting The Table
$result = mysql_query("SELECT * FROM posts")
or die(mysql_error());
// Connecting To The Rows, And Echoing Back The Results
while($row = mysql_fetch_array($result)) {
echo "<div class='post'>";
echo "Title: " . $row['title'];
echo "<br />";
echo $row['content'];
echo "</div>";
I am not sure how to make the latest post the first to show up.
I still want it to echo back the older entries though.
I can use phpMyAdmin if necessary.
You need to order your results.
SELECT * FROM posts ORDER BY date_posted DESC
I am new to PHP and am making a social network as practice and to apply what I have learned in the "real world". Anyhow, I have two tables in a MySQL database that i am trying to display on my site in the same html table that is being rendered through an php echo.
here are the tables
(table1)
note_system:
-id,
-username,
-note
(table2)
comments:
-id,
-cid (equals id from note_system),
-username,
-comment
so someone makes a post and it saves to the note_system table then someone comments on the post and it saves to the comment table with the id from the note_system table so a relation can be established.
So what I am trying to do is get the post comments to display with the relevant post. I have gathered that I need maybe a JOIN or UNION to make this happen but I am at a complete loss on how to do it. Been racking my brain and doing tons of google searches but I am not really getting anywhere. Everything I try gives me errors. The Notes display just fine and as intended but I can't for the life of me figure out how to get the comments to show up there too.
Here is my code (don't laugh at the noob-ness of my PHP, this is my 2nd PHP program ever and I obviously have much to learn, I would like to clean it up at some point but for now I just want it to be functional)
<?php
// Display Note_Wire
$con=mysqli_connect($host,$username,$password,$dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//format and display the Note_Wire results with comments
$result = mysqli_query($con,"SELECT * FROM note_system");
while($row = mysqli_fetch_array($result))
{
echo "<center>";
echo "<table class='note_wire'>";
echo "<tr>";
echo "<td>" . $row['username'] . "</td>" ;
echo "</tr><tr>";
echo "<td><a href=''>vote up</a>" . " " . $row['rank'] . " " . "<a href=''>vote down</a></td>" ;
echo "</tr><tr>";
echo "<td> <a href='{$row['link']}' target='blank'>{$row['link']}</a>";
echo "</tr><tr>";
echo "<td>" . $row['note'] . "</td>" ;
echo "</tr> ";
//add comments attempt this is where I would like the comments to be displayed
echo '
<td><form action="add_comment.php" method="POST">
<input type="hidden" name="username" value="';
echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
echo '" />';
echo '<input type="hidden" name="cid" value="';
echo $row['id'];
echo '" />';
echo '<textarea name="comment">comment...</textarea></td></tr>
<tr><td><input type="submit" value="comment" />
</form></td></tr>
';
echo "</table>";
// break before next note-wire record renders
echo "<br />";
}
echo "</center>";
?>
I hope my chicken scratch programming makes sense. Thanks for your time and knowledge.
Really the comments are a different data set from the actual post you could just use a second query to get all of the comments related to the post. But table joins are very useful and you should learn them. In this case you would join the note_system and comments table on the shared ID (the foreign key).
So like so:
SELECT *
FROM note_system
LEFT JOIN comments ON comments.cid=note_system.id
This is a literal joining of the tables so your output will include all columsn from both tables as long as there is a match for the joining expression. If there isn't a CID column in the comments table that matches then the values for those columns will be NULL in your output. (If you wanted to only return rows where there is a match you could use an INNER join as opposed to the LEFT OUTER join I've used above.)
This is a good page explaining SQL table joins.
Heres the basics step for you if your a beginner in using php and mysql..
FIRST : SET UP CONFIGURATION FOR DATABASE USER,PASS,HOST,DBNAME
$conn = new mysqli('database_server','database_username','database_password','database_name');
SECOND : Create a Query(you may insert your query here)..
$result= $conn->query("SELECT SUM(Total_Steps) AS value_sum FROM users");
FINAL : SHOWN RECORDS USING MYSQL FUNCTIONS LIKE..
while($row = $result->fetch_assoc()){
echo $row['dabatase_columnname'];
echo $row['database_columnname'];
}
for your query try to use this one or either create a relative one.
SELECT 'enter column needed here with their specific database allias ex. TABLE1.ID'FROM NOTE_SYSTEM TABLE1 LEFT JOIN COMMENTS TABLE2 ON TABLE1.ID = TABLE2.CID;
Ok, so I'm trying to make some simple code to display news articles from a MySQL server but all I get is a completely blank middle part of the page where the news articles are supposed to be. Here is the code:
<?
$query = "SELECT ID, header, content FROM news ORDER BY ID DESC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo "<div class=\"newsItem\">";
echo "<h2>" . $row['header'] . "</h2>";
echo "<p>" . $row['content'] . "</p>";
echo "</div>";
}
?>
The problem seems to be with the while loop. If I write echo "WTF"; outside the loop it will show but if i write it inside it wont show. I'm not really good at PHP so I'm puzzled. ID is INT and Primary Key, header is VARCHAR(255) and content is TEXT. Any Ideas? Also the connect scrips works cuz I dont get error messages when it dies.
Try adding an error catch:
$query = "SELECT ID, header, content FROM news ORDER BY ID DESC";
$result = mysql_query($query) or die(mysql_error());
OR you have no results. so add somthing for that:
if(mysql_num_row($result) > 0){
while($row = mysql_fetch_array($result))
{
echo "<div class=\"newsItem\">";
echo "<h2>" . $row['header'] . "</h2>";
echo "<p>" . $row['content'] . "</p>";
echo "</div>";
}
}
else {echo 'no results';}
You either have no records in your news table or displaying warnings isn't enabled (slap)
There aren't any news in news table
One or more columns are missing
Table news does not exists
in your case, try to replace your 2nd line with
$query = "SELECT ID, content FROM news ORDER BY ID DESC";
You may have a database rights issue or your query may have an error but the error isn't being displayed.
If you don't have display_errors turned on in your php.ini, you should take a look in the web server error log file to see if an error is being logged when you connect to the MySql database.
You could also try:
ini_set('display_errors', 1);
At the top of your script which will force any database connection or query errors to be displayed in the resulting web page.
NOTE: This is a feature to support your development and should never be used on production systems.
I've spent the last few days wrestling with a MYSQL query issue. I hope someone can point me in the right direction.
I'm querying two tables ('questions' and 'comments') with the goal of returning the following layout:
Question 1
Comment 1
Comment 2
Comment 3
Question 2
Comment 4
Comment 5
And so on...
Comments are unique to a question (i.e. comments live under a parent question).
My query (which I know is incorrect) looks like this:
<?php
$query = "SELECT discussion.*, comments.* FROM discussion LEFT JOIN comments ON discussion.referenceID = comments.commentID";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['question']. " - ". $row['comment']. "<br /><br />";
}
?>
The result:
Question 1 - Comment 1
Question 1 - Comment 3
Question 2 - Comment 2
I'm close, but can't achieve the multiple comments under the single question. I tried a 'GROUP BY discussion.question' but that limited my results to:
Question 1 - Comment 1
Question 2 - Comment 2
To put it in context I'm trying to allow users to submit comments on multiple questions displayed on a single page.
Thanks in advance.
RR
try this:
$query = "SELECT *
FROM discussion, comments
WHERE discussion.referenceID = comments.commentID
GROUP BY discussion.referenceID;
Just store the previous question and compare it to the current.
Sketch:
$prev_question = null;
while($row = mysql_fetch_array($result)) {
if ($prev_question != $row['question']) {
echo '<b>' . $row['question'] . '<b><br />';
$prev_question = $row['question'];
}
echo $row['comment'] . '<br />';
}
Zerkms, brilliant! Thanks for the response. Works perfectly, aside from one issue.
The questions only appear if there is a comment associated (an issue I caused myself, at some point). The goal is to display all comments regardless of if comments are assigned.
Working code:
<?php
$query = "SELECT discussion.*, comments.* FROM discussion LEFT JOIN comments ON discussion.referenceID = comments.commentID";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$prev_question = null;
while($row = mysql_fetch_array($result)) {
if ($prev_question != $row['question']) {
echo "<h3>" . $row['question'] . "</h3>";
$prev_question = $row['question'];
}
echo "<img src=\"images/bg_addform_topFull.gif\" width=\"446\" height=\"11\" /><div class=\"comment\"><h3>" . $row['author'] . "</h3><div class=\"greyText\">" . $row['dt'] . "</div><p>" . $row['comment'] . "</p></div><img src=\"images/bg_addform_bottom.gif\" width=\"446\" height=\"11\" class=\"footerImage\" />";
}
}
?>
Again, thanks for the help.