Selecting data from 2 tables with PHP - php

I am relatively new to PHP and SQL and I am creating a simple blog tool for my own page and I'm stuck on how I can make a comment section.
I have 2 tables
general, which contains the blog post and additional information
comments, which contains comments
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "blog";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die ("connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM general WHERE hidden = 'false' ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0){
while ($row = $result->fetch_assoc()){
echo "<div class='blogpost'>
<div class='blogbody'></div>";
//I need to do a query into the comments table at this point to find
//all comments matching the criteria to be matched with the post here.
echo "<div class='comments'></div></div>";
}
}
else{
echo "no posts";
}
I manage to get the blogposts working but as soon as I try a second query by adding
$conn2 = new mysqli($servername, $username, $password, $dbname);
if ($conn2->connect_error){
die ("connection failed: " . $conn2->connect_error);
}
$sql2 = "SELECT * FROM comments WHERE $row["parent"] ORDER BY id DESC";
$result2 = $conn2->query($sql2);
if ($result2->num_rows > 0){
while ($row2 = $result2->fetch_assoc()){
}
}
else{
echo "no comments";
}
it all just breaks. I am not able to throw in a loop that gets all the comments for the specific post before it starts loading additional posts.
How would I go on about solving this? I might need a little spoonfeeding with comments in any code samples,

You can use the primary key of the post and that can be used in comments table as a foreign key so that you can easily make your query with that will show all the comments against that specific post. Then the query will be like this:
$postid=$row['post_id'];
$sql2 = "SELECT * FROM comments WHERE post_id='$postid' ORDER BY post_id DESC";

Changing the second query to fixed the problem.
WHERE $row["parent"] ORDER. Change that to WHERE parent={$row['parent']} ORDER
Thanks to Jeff for providing this answer

Related

Is it possible to loop through each row of a table in a database

I'm trying to loop through each row of a table in a database, then once I'm on a particular row get the value of a certain column. Is this possible? I've done a couple Google searches but nothing really concrete. I try using the mysqli_fetch_array() function but when I do I get the results of a column. I want to target each row. The code I have so far gets me the "nid" column. That's not what I want. I want to iterate through each row.
<?php
$serverName = "localhost";
$username = "user1";
$password = "sp#99#1";
$databaseName = "developer_site";
// Connection
$connection = new mysqli($serverName, $username, $password, $databaseName);
// Check Connection
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
} // line ends if statement
$queryNodeRevision = "SELECT nid FROM node_revision";
// line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
echo "NID: ";
echo $row['nid'];
echo "<br/>";
}
?>
You can select rows by a certain condition with an SQL query alone and also select all columns.
SELECT * FROM node_revision where condition;
condition could be anything. For example another_row = 'something'.
But if, for some reason, you need to process the nid inside your php script to know if that row is the "particular" one you're searching, then you just select all the columns, or the ones you need.
$queryNodeRevision = "SELECT nid, col1, col2 FROM node_revision";
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
if (condiiton) {
echo "Particular: ".$row['nid']
." ".$row['col1']
." ".$row['col2'];
}
}
condition could be something like $row['nid'] == 123 for example.
Hope it helps.

second sql query based on the first one

i want to take the result of an sql query "user_id"and search using it in
in another query in another table
for example :
main query select * from tracker
second query: take the id from the first query to replace it with the name of the user found in another table "user table".
something like :
select user_name from vtiger_users where id = $row["id"]
here is my code below
<?php
$servername = "localhost";
$username = "x";
$password = "xyz";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, module, whodid,changedon FROM vtiger_modtracker_basic";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table style='float: left'><tr><th>ID</th><th>Module</th><th>Who Did</th><th>Time Of Action</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
$user_id=$row["id"];
$username_sql="SELECT user_name FROM vtiger_users where id=".$user_id." ";
$result_username=$conn->query($username_sql);
$row2 = $result_username->fetch_assoc();
echo "<tr><td>".$row["id"]."</td><td>".$row["module"]."</td><td>".$row2["user_name"]."</td><td>".$row["changedon"]."</td></tr>";
//echo "<p>".$row2["user_name"]."</p>"
//echo $row2["user_name"];
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
I guess you should use whodid column when you set $user_id = $row['whodid'] or you can use JOIN query. It will return you user_name from vtiger_users table.
SELECT
a.id,
a.module,
a.whodid,
a.changedon
b.user_name
FROM vtiger_modtracker_basic a
JOIN vtiger_users b ON a.whodid = b.id
thanks all ,that query did the job for me
SELECT vtiger_modtracker_basic.id, vtiger_modtracker_basic.module, vtiger_modtracker_basic.whodid ,vtiger_modtracker_basic.changedon ,vtiger_users.user_name FROM vtiger_modtracker_basic ,vtiger_users where vtiger_modtracker_basic.whodid = vtiger_users.id

MySQL query with output to PHP page

I am trying to make simple page which will return values from MySQL table, but the problem is that if I want to use condotions in query then it doesn't work.
My PHP page:
<?php
$servername = "10.10.10.10";
$username = "username";
$password = "password";
$dbname = "GENERIC_TABLES";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT WO_NUM+1 from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> WO Number ". $row["WO_NUM"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
So, WO_NUM column has numbers like 1, 2, 3 etc.
I want to get the last one + 1
So if I do like:
$sql = "SELECT WO_NUM from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1";
Then it works fine, but if I want to make it WO_NUM + 1 then it returns nothing.
Why it happens like that and is there any way to get what I want using MySQL?
I don't want to get WO_NUM and then using PHP make it + 1, since I also need INSERT to the table values and I would like to understand why it doesn't work.
As you realized, WO_NUM+1 changes the column name in the resulting array, so use an alias WO_NUM+1 as NEW_NUM. However I would not bother with the sorting and limit. Consider MAX():
SELECT max(WO_NUM)+1 as NEW_NUM from GENERIC_TABLES.WO_NUMBERS
As it has been pointed by AbraCadaver, I missed that if I am using WO_NUM + 1 then column name changing so that is why i didn't get any output, so using alias solved problem.

php sql How to display only the last value in the row?

I need only to display the last values in the row. Now its displaying
Message for: Rocha : gff
Message for: Rocha :
Message for: Rocha : hi my name is kenny
I only need it to display Message for: Rocha : hi my name is kenny.
Thank you
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "company";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, className, lastname, messages FROM Mymesages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if("CPS210-CompSci-I (4)"==$row["className"] && $lastname== $row["lastname"]){
echo "Message for: " . $row["lastname"]. " : " . $row["messages"]. "<br>";
}
}
}
$conn->close();
?>
If you're looking for only one record, that too the last one, you just need to modify your query a little. Also, there's no need for the loop in that case.
$sql = "SELECT id, className, lastname, messages FROM Mymesages ORDER BY id DESC LIMIT 1";
Replace this line:
while($row = $result->fetch_assoc()) {
With simply:
$row = $result->fetch_assoc();
If you want to display the last row, then your query should be like this:
$sql = "SELECT id, className, lastname, messages FROM Mymesages ORDER BY id DESC LIMIT 1";
And later, instead of while loop simply fetch the row like this:
$row = $result->fetch_assoc();

Trying to display values from a SQL table, recieveing error, trying to get property of non-object

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "comp4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT OrderID, id, items FROM orders WHERE id= $user";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$results = $row["OrderID"]. " " . $row["id"]. $row["items"]. "<br>" ;
}
$loop = implode( " ", $items );
echo $loop;
}
?>
So, I have this code and I'm trying to display OrderID, id and items from the user thats logged in $user=whoever's logged in that's in a different part of my code, however I keep getting an error
Notice: Trying to get property of non-object in C:\xampp\htdocs\myorders.php on line 35
After looking around, I'm still not quite sure how to fix this. Any help is appreciated
I'm guessing your error lies in this line of code:
$sql = "SELECT OrderID, id, items FROM orders WHERE id= $user";
It could be that ID is a reserved keyword of SQL, or that $user is undefined and/or not a numeric value.
Try the following:
$sql = "SELECT `OrderID`, `id`, `items` FROM `orders` WHERE id = $user";
The reason for the error is your query fails. Then you later do the following:
if ($result->num_rows > 0) {
And since the query failed, $result is not an object, and you try to access num_rows of this non-object.
Of course I am only guessing because we need more information :)

Categories