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;
Related
very new to php and mysql so all help is greatly appreciated. I have tried to search the forums but not entirely sure specifically what I need to be searching for. I have a form which ask users to select a product and make a comment.
I need the information for a particular product to show on my product page instead of all of the information. (for example, I want the reviews for iPads to show on the ipad page)
This is the code that send the data to the database:
<?php
session_start();
include('connection.php');
$name=$_POST['name'];
$product=$_POST['product'];
$star=$_POST['star'];
$comment=$_POST['comment'];
mysql_query("INSERT INTO tt_review(name, product, star, comment)VALUES('$name', '$product', '$star','$comment')");
header("location: https://scm-intranet.tees.ac.uk/users/l1071039/tablet-takeover/index.html");
mysql_close($con);
?>
This is the current code to fetch the data onto my page:
<?php
include('connection.php');
$result = mysql_query("SELECT * FROM tt_review");
echo "<table border='1'>
<tr>
</tr>";
while($row = mysql_fetch_array($result)) //This function is calling the results variable and displaying them within the rows below
{
echo "<tr>"; //this code tells the page to output the table rows that are defined above
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['date'] . "</td>"; //each row is then executed using the table data function
echo "<td>" . $row['product'] . "</td>";
echo "<td>" . $row['star'] . "</td>";
echo "<td>" . $row['comment'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
This is a screenshot of the table on my webpage (as I say, I need it to only show the ipad reviews.
To select only one kind of product, you should add a where clause on your sql query:
SELECT * FROM tt_review WHERE product = 'Apple iPad'
You can give like this
"SELECT * FROM tt_review WHERE Product_name ='ipad'"
It will display only the information related to Ipad
Still If you dont understand please give me the name of the columns you used in the table
Firstly, mysql_* functions have been depreciated. Rather, use either PDO or MySQLi.
Secondly, your code is very vulnerable to SQL injection.
Thirdly, fix your select statement to the following:
SELECT * FROM tt_review WHERE product = 'ipad'
I'm doing a project where I have to take in information from a user on a web page and store it in a MySql database. Some of the fields the user has to fill out are his street number, name and suburb and these are separate fields and are stored as separate values in the database.
So, part of the project is to display all of the entries in a table, but combine the info from above (Street no, name, suburb) and display it together in one cell under the heading 'Address' so it shows as full address.
So my question is, what are some ways of doing this?
Everything is working so far and I can display each field individually, so it's just the question of formatting.
Hopefully, you guys can give me a hand,
Cheers!
EDIT: This is how I'm displaying the table right now:
$QueryResult = mysql_query("SELECT * FROM booking");
$row = mysql_fetch_row($QueryResult);
echo "<table width='100%' border='1'>";
echo "<tr><th>Booking No</th><th>Passanger Name</th><th>Phone</th><th>Unit</th>";
echo "<th>Street No</th><th>Street Name</th><th>Pick-up Suburb</th><th>Destination Suburb</th>";
echo "<th>Pick-up Date</th><th>Pickup time</th></tr>";
$countRows = 0;
$tweight=0;
while($row){
$countRows++;
echo "<tr><td>{$row[0]}</td>";
echo "<td>{$row[1]}</td>";
echo "<td>{$row[2]}</td>";
echo "<td>{$row[3]}</td>";
echo "<td>{$row[4]}</td>";
echo "<td>{$row[5]}</td>";
echo "<td>{$row[6]}</td>";
echo "<td>{$row[7]}</td>";
echo "<td>{$row[8]}</td>";
echo "<td>{$row[9]}</td></tr>";
$row = mysql_fetch_row($QueryResult);
}
How would I use CONCAT in this case?
Thanks
In php:
$address = $row[4] . ' ' . $row[5] . ' ' . $row[6];
In mysql:
SELECT CONCAT(street_no, ' ', street_name, ' ', suburb) AS address FROM ...
Choose one of them and change this code depending on the variable names you have.
This is probably a really obvious error. Anyway, some details:
I have an oracle database that I need to extract data from to populate a table on a PHP page. The table is called Flowers and has Name, Price and Stock columns.
The part of the PHP code I'm having trouble with is this:
$titlevalue = Trim($_REQUEST['search']);
$query = "SELECT * FROM FLOWERS WHERE NAME = '$titlevalue'";
$stmt = OCIParse($connect, $query);
if(!$stmt) {
echo "An error occurred in parsing the sql string.\n";
exit;
}
OCIExecute($stmt);
The rest of my PHP works -perfectly- when using a different table on my database, which I did as a test. Just in case, this is the code that prints the query results (it's part of an HTML table, but you can ignore that):
while(OCIFetch($stmt)) {
echo "<tr valign=top bgcolor=#F7D4A3>";
$fg1 = OCIResult($stmt,"NAME");
echo "<td width=75>";
echo $fg1;
echo "</td>";
// Display values in column two.
$fg2 = OCIResult($stmt,"PRICE");
echo "<td width=75>";
echo ($fg2);
echo "</td>";
// Display values in column three
$fg3 = OCIResult($stmt, "STOCK");
echo "<td width=75>";
include($fg3);
echo "</td>";
echo "</tr>";
}
No matter what $titlevalue becomes, I just can't get results with this table. I have also tested it with a generic $query = "SELECT * FROM FLOWERS";, but that didn't produce anything either.
Could someone please lend a hand? :( It's been a very long night.
If I may, two things just to note:
1) you're using '$titlevalue', i think that will translate as ... $titlevalue in the query, and not its value
2) Its late ... have you checked that your table is called FLOWERS (case sensitivity)
I'd comment, but I dont have the rep to do so.
If this was helpful, please +1 or click the tickmark. I normally try and use the full format when doing sql queries
SELECT * FROM `table name` WHERE 'x'
... etc. where possible
Let me start off that I have only been coding for the past few months. I know I've probably got a ton of mistakes or bad practices everywhere. I like constructive criticism, so please let me know what i can do better, along with how to address my current issue.
This code's purpose is to create a table of part numbers, and their associated location column data (storage type, Rack number, Shelf number) based on previously entered information. I've got the entry form working perfectly. I type in a number of parts I want to search for, and it posts that number back to itself. I'm then presented with that number of text input fields to put in part numbers.
//this form is to submit the number of parts you're looking for,
//and posts back to itself
<form action=View2.php method="post">
<input type="text" name="num">
<button type="submit">Number of Parts</button>
</form>
//This form takes the posted number, and creates that many text fields,
//populated with the number part you are entering.
<form action="List.php" method="post">
<?php while ($i<=$num){
echo "<input type='text' name='part$i' value='part$i'><br><br>";$i++;}?><input type="hidden" name="num" value="<?php $num?>">
<button type="submit">Submit</button>
</form>
My problem comes with running a mysqli_query to populate the table. I'm stuck as to where to go from here. I know that i need to take each part number that gets posted, and use it as the criteria in a SELECT WHERE search, so i made this While loop:
<?php
echo "<table border='1'>
<tr>
<th>Part Number</th>
<th>Location</th>
<th>Rack</th>
<th>Shelf</th>
</tr>";
while($i<=$num){
$x=$_POST["part$i"];
$result = ($con,"SELECT * FROM parts WHERE pn ='$x'");
$row = ($result);
echo "<tr>";
echo "<td>" . $x . "</td>";
echo "<td>" . $row['rcb'] . "</td>";
echo "<td>" . $row['ra'] . "</td>";
echo "<td>" . $row['sh'] . "</td>";
echo "</tr>";
$i++;
}
echo "</table>";?>
The page crashes at this point, but if i comment out the $result line, i'll get the table with the part number fields populated with the values from the previous page.
Anyone have any idea what i'm doing wrong, or how i can do it better?
This line doesn't do anything good :
$result = ($con,"SELECT * FROM parts WHERE pn ='$x'");
You need to actually query the DB.
$mysqli = new mysqli("localhost", "my_user", "my_password", "...");
...
$result = $mysqli->query("SELECT * FROM parts WHERE pn ='$x'");
You should use prepared statements so your code isn't open to sql injections though...
I am trying to build an online reading test for my students. I currently have two tables in my database : 'student' and 'questions'. In 'student', I have a row for each student which containts it's name, group number and answers to the questions. Questions cols are called question[1], question [2], and so on.
In 'questions', I have 4 cols : ID, 'first', 'chapter' and 'question'. 'first' is a true/false field, if it is the first question to a chapter its value is 1. I call those with a while loop.
echo '<ol>';
$query = mysql_query("SELECT * FROM `question`");
while($row_q = mysql_fetch_assoc($query)) {
if($row_q['first']==1){
echo '<h2>Chapter '.$row_q['chapter'].'</h2><br>';
}
echo '<li>';
echo $row_q['question'];
echo '</li>';
echo '<br>';
}
echo '</ol>';
It echoes beautifuly. Now, I'm trying to put an input field under each question so the student can give an answer and submit it at the end of the page. How can I do this? I tried using a for($i=1;$i<=10;$i++) statement since I want each field to be named with a different number, but no matter where I insert it, I either end up with a bunch of identical fields next to each other or my questions echoed over and over again.
I'm open to all suggestions. Thanks!
there's no need to do a for loop, you're already in a loop :) just set a variable called question number and increment it in the while loop.
$question_number =1;
echo '<ol>';
$query = mysql_query("SELECT * FROM `question`");
while($row_q = mysql_fetch_assoc($query)) {
if($row_q['first']==1){
echo '<h2>Chapter '.$row_q['chapter'].'</h2><br>';
}
echo '<li>';
echo "<label>$question_number".$row_q['question']."</label>";
echo "<input type='text' name='$row_q[\'ID\']'></input>";
echo '</li>';
echo '<br>';
$question_number++;
}
echo '</ol>';
echo '<input name="answer[' . htmlspecialchars($row_q['ID']) . ']" type="text" value="" />';
under the question text... Then in PHP var_dump($_REQUEST) to see the answers...
EDIT:
For displaying the saved answer, you'll want to do something like this:
echo '<input name="answer_' . $idx . '" type="text" ' .
value="' . htmlspecialchars($student_row["answer_$idx"]) . '" />';
and maintain a counter $idx as you loop...
That's if your answer are laid out flat in the student table per your description and the answer value columns are named "answer_1" etc.
If the answers are normalized in a separate table, you can join the tables together:
select * from question q left join answer a on a.question_id = q.question_id and
a.student_id = <current student id>