Use Query Result Row in Another Query - php

I'm trying to use the row from a query in another query.
This query correctly displays the username of the user currently signed in:
$param = $fgmembersite->UserEmail();
$query = mysqli_query($con, "SELECT username FROM Users1 WHERE email = '$param'
");
while ($row = mysqli_fetch_array($query)){
echo $row['username'] ;
}
I'm trying to find a way to use $row['username'] in another query something like...
$sql = mysqli_query($con, "SELECT * FROM messages WHERE to_user = '" . $row['username'] . "' ");
This doesn't give me a coding error, but it doesn't work. The username row obviously can't be taken from a separate query the way I'm attempting.
I have tried every combination I can think of but nothing has worked for me. Any help greatly appreciated.

Try a subquery
SELECT * FROM messages WHERE to_user in (SELECT username FROM Users1 WHERE email = '$param')

You can join the queries into one:
SELECT `messages`.*
FROM `messages`
JOIN `Users1`
ON `Users1`.`username`=`messages`.`to_user`
WHERE
`Users1`.`email`='$param'

Well you should place your second query inside while:
while ($row = mysqli_fetch_array($query)){
echo $row['username'] ;
$sql = mysqli_query($con, "SELECT * FROM messages WHERE to_user =
'" . $row['username'] . "' ");
}
Now loop ends when mysqli_fetch_arrray returns NULL and that NULL you are trying to insert into second query.

You can combine the two queries into one.
SELECT * FROM messages WHERE to_user = (SELECT username FROM Users1 WHERE email = '$param')

Related

What is an SQL query for counting records that are existing more than once in a database?

<?php
mysql_connect("localhost", "root", "");
mysql_select_db("students");
$id = $_POST['id'];
$grade = $_POST['grade'];
$query = "INSERT INTO `st_table` (`St_id`,`Grade`) VALUES ('$id','$grade')";
$result = mysql_query($query);
$query = "SELECT * from `st_table`";
$result = mysql_query($query);
echo "<table>";
echo "<th>St_id</th><th>Grade</th>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['St_id'] . "</td><td>" . $row['Grade'] . "</td></tr>";
}
This code adds values into a table both ID and Grade. I want another query that will be able to count how many As, Bs, Cs, etc. and OUTPUT it on an html table.
Here, Your query is ok just group by Grade not Grades
"SELECT `Grade`, COUNT(*) AS count FROM `st_table` GROUP BY `Grade`";
Here is sqlfiddle
After edit
The query i am mentioning should work for you, you can check fiddle for that as for as you modified code is concerned you have to change your table a bit since you are going to include St_id as well so make it 3 column and correspondingly change query too.

Getting extra data in MYSQL count query

Hi all i've had help from bluefleet (BF) with a mysql query which i've now put in a php file, the query works fine but i find i need to get extra data as well as the count, so what i need is when a match is found i need to look up the username in table tview3.
Whichever table the ip match is found there will be a column called UID, in the table tview3 there will also be a column called USERNAME, what i'd like to do is get the username(s) for the matches and then use them in a text file.
I have to state i'm a complete newbie at this, all help is appreciated
$myquery= "select sum(total)
from
(
SELECT count(*) as total
FROM " .TABLE_PREFIX."tview v
where v.ipaddress = '$ips'
union all
SELECT count(*) as total
FROM " .TABLE_PREFIX."tview2 v1
where v1.ipaddress = '$ips'
union all
SELECT count(*) as total
FROM " .TABLE_PREFIX."tview3 v3
where v3.ipaddress = '$ips'
) src";
$result = mysql_query($myquery);
$rowCount = mysql_num_rows($result);
If($rowCount !=0){
echo "NOT EMPTY";
}else{
echo "EMPTY";
}
mysql_free_result($result);
$UAM = strtoupper($_SERVER['HTTP_USER_AGENT']);
$ips = strtoupper($_SERVER['REMOTE_ADDR']);
$fp = fopen("logtext.txt", "a");
$DateOfRequest = date('m-d-Y H:i:s');
fwrite($fp, "$DateOfRequest . \nMatched Member: . $username . \nWith User Agent: . $UAM . \n\nIP: . $ips . \n\n");
So i'd like to populate a variable $username with the username(s) where the matches were found.
Regards,
Silo
Change:
SELECT count(*) as total
to
SELECT count(*) as total, username
Then you could do something like:
$row = mysql_fetch_array($query);
$username = $row['username'];
Hope that helps. Also check out this question for a bit more detail: How do I find the most common result in a column in my MySQL table

Putting 2 WHERE statements together

I'm having problems putting two where statements together
My current code:
include 'config.php';
$result22 = mysql_query("SELECT * FROM messages WHERE to_user='".$_SESSION['username']."' AND to_read_yet='yes' ");
$num_rows22 = mysql_num_rows($result22);
echo "$num_rows22 ";
For some reason this isn't working. I am not getting any results i have checked the db and there are results which should come out
You should read about sql syntax. After where you put any number conditions with bool operators. Using 2 times where is incorrect
$result = mysql_query("SELECT * FROM messages WHERE to_user='".$_SESSION['username']."' AND to_read_yet='"no"' ");
Leave the second WHERE expression out, it's just WHERE condition_1 AND condition_2 AND condition_3 AND ....
$result = mysql_query("SELECT * FROM messages WHERE to_user='".$_SESSION['username']."' AND to_read_yet='"no"' ");
SELECT *
FROM messages
WHERE to_user = '".$_SESSION['username']."'
AND to_read_yet= '"no"'
try with:
$result = mysql_query("SELECT * FROM messages WHERE to_user='".$_SESSION['username']."' AND to_read_yet='no' ");
$result = mysql_query( "SELECT * FROM messages WHERE to_user='" . $_SESSION['username'] . "' AND to_read_yet='no'" );
Drop the second WHERE

what is wrong with this code?

I need to read a text file, query the database table with that name, and store that table's data in another table. So far I have written this code but I don't know why it's not working.
foreach ($lindb as $namedb) {
$query = "SELECT * FROM ntable WHERE name =" .$namedb. "";
$result = mysql_query($query);
while ($r = mysql_fetch_array($result)) {
$query = "INSERT INTO ndtable (name,details,address,login,country) VALUES (\"".$r["name"]."\", \"".$r["details"]."\", \"".$r["address"]."\", \"".$r["login"]."\", \"".$r["country"]."\")";
mysql_query($query);
}
}
You don't have quotes around $namedb
ie. SELECT * FROM ntable WHERE name =" .$namedb. ""; should be SELECT * FROM ntable WHERE name ='" .$namedb. "'";
I suggest a SELECT INTO would be the better choice... and please post the error so we are able to help...

PHP query multiple Tables

I'm having trouble getting any information to display from this query. Anyone know where I'm going wrong?
Thank you!
$query = "SELECT * ".
"FROM comments, users ".
"WHERE comments.user_id = users.user_id ".
"ORDER BY comments.date DESC ".
"LIMIT 10";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row['users.user_id'];
echo $row['comments.comment'];
}
use mysql_fetch_assoc() instead of mysql_fetch_array().
In your loop use the column name as the array key:
while ($row = mysql_fetch_assoc($result)) {
echo $row['column_name1'];
echo $row['column_name1'];
}
In your query try to be more specific on the select statement, try not to use *.
You're probably getting the error because you are sorting (ORDER BY) on a field that does not exist in your query.
It would be best practice to not use the "SELECT *" querying. If all you need are specific values, specify them. This also helps when retrieving the data...
$query = "SELECT users.user_id, comments.comment, comments.date ".
"FROM comments, users ".
"WHERE comments.user_id = users.user_id ".
"ORDER BY comments.date DESC ".
"LIMIT 10";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row['user_id'];
echo $row['comment'];
echo $row['date'];
}
It is good practice to specify column names in a query rather than using * - on some DBs there is a performance impact and on all it prevents any unexpected behaviour cropping up from table changes.
In the example I think the issue is arsing from the array keys you are using - you don't need to include the table name in them, just the column name:
echo $row['user_id'];
echo $row['comment'];
The better practice is to write only fields what you need in your sql query like this:
$query = "SELECT u.user_id uid, c.comment comment ".
"FROM comments c, users u ".
"WHERE comments.user_id = users.user_id ".
"ORDER BY comments.date DESC ".
"LIMIT 10";
Using so type of queries you reduce the time of executing your query and transmitting data from database server to your php script. After this modification your cycle transformed to:
while ($row = mysql_fetch_array($result)) {
echo $row['uid'], $row['comment'];
}
I use PDO method but this can work for you too:
<?php
$sql = "SELECT * FROM comments as c INNER JOIN users as u ON c.user_id=u.user_id WHERE u.user_id=:user_id ORDER BY c.date DESC LIMIT 10";
//prepare the connection to database
$prep = $conn->prepare($sql);
//change the parameters for user_id on WHERE condition you can put anything you want but i will put the user session id
$prep->bindParam(":user_id", $_SESSION['user_id']);
$prep->execute();
//ill use fetchAll function because it can be more than 1 comment
$datas = $prep->fetchAll();
foreach($datas as $data){
echo $data['user_id'];
echo $data['comment'];
echo $data['date'];
}
?>

Categories