using values from a query in another query - php

i have a query
$result = mysql_query("SELECT * FROM comprofiler WHERE cb_playstationgames LIKE '%FIFA%' ORDER BY id ASC");
in that query there is a user_id wich i need to perform a query on another table.
$gebruikerid = mysql_query("SELECT * FROM users where id LIKE '".$result['user_id']."'");
Now i want to use that value in a while loop
echo "<table><tr><th width=\"300\" align=\"left\" >Avatar</th><th width=\"300\" align=\"left\">Naam</th><th width=\"200\" align=\"left\">PSN Naam</th></tr>";
while($row2 = mysql_fetch_array($result))
{
echo "<tr><td><img height=\"50\" width=\"50\" src=\"/images/comprofiler/" . $row2['avatar'] . "\"></td><td>" . $gebruikernaam . "</td><td>" . $row2['cb_psnnaam'] . "</td></tr>";
}
echo "</table>";
I cannot get the query to read the values from the other table based on the id from the first table. Can someone help me?

In your case the best solution it's to use JOIN.
$result = mysql_query("SELECT comprofiler.*, users.* FROM comprofiler INNER JOIN users ON users.id = comprofiler.user_id WHERE cb_playstationgames LIKE '%FIFA%' ORDER BY comprofiler.id ASC");
You may have to manually specify the columns you want to select (after SELECT ) in case that you have same column names in both table and you need both.
$result = mysql_query("SELECT comprofiler.id as id_comprofiler, users.id as id_user, users.avatar ... " );

To answer your question why it does not work:
Second query does not use mysql_fetch_array.
$gebruikerid = mysql_fetch_array($gebruikerid);
It would be more secure & cleaner if you would use PDO or MySQLi prepared statements like:
$db = new \PDO(SEE PDO CUNSTRUCT)
$query1 = $db->prepare('
SELECT *
FROM comprofiler
WHERE cb_playstationgames LIKE :fifa
ORDER BY id ASC
');
$query2 = $db->prepare('
SELECT * FROM users where id LIKE :id
');
$query1->bindValue(':fifa', '%FIFA%', PDO::PARAM_STR);
$query1->execute();
while ($row = $query1->fetch(PDO::FETCH_ASSOC)) {
$query2->bindParam(':id', $row['user_id'], PDO::PARAM_INT);
$query2->execute();
//Holds associative array of second query
$row2 = $query->fetch(PDO::FETCH_ASSOC);
//$row1 holds associative array of first query
}

Related

How to retrieve data from multiple tables using a PHP form?

I want to retrieve data from multiple tables using dot operator/join where arguments are passed from an HTML/PHP form.
HTML CODE
<input name="rollno" type="text" placeholder="Roll Number" required>
<input name="submit_view_details" type="submit" value="Proceed">
PHP CODE
if(isset($_POST['submit_view_details']))
{
$rollno = (int) $_POST['rollno'];
$query = "select * from table1, table2 where table1.{$rollno}=table2.{$rollno}";
$result=mysqli_query($connection,$query);
}
In the browser if enter the input 1 and echo this query then it looks like follows:
select * from table1, table2 where table1.1=table2.1
and no row is fetched despite of having data in the table(s).
it only works if the query looks like follows:
select * from table1,table2 where table1.rollno=table2.rollno
However, in that case it fetches all the rows but I need only the row of the rollno that user entered in the above mentioned form.
I am just not able to work this out. Help would be much appreciated. Thanks!
Use the AND keyword to specify the rollno.
SELECT * FROM table1, table2 WHERE table1.rollno = table2.rollno
AND table1.rollno = {$rollno};
You could probably use the keyword JOIN instead like this :
SELECT * FROM table1 NATURAL JOIN table2
WHERE rollno = {$rollno};
You need joins
take a reference of joins from here,
i am sure it will help
http://www.tutorialspoint.com/mysql/mysql-using-joins.htm
You should use join like this
$query = "SELECT tbl1.*, tbl2.*
FROM tbl1
INNER JOIN tbl2 ON tbl1.id = tbl2.id
WHERE tbl1.column = value ";
foreach ($pieces_2 AS $value) {
$pieces_3[] ="(CONCAT_WS('|',$presql2) like '%$value%')"; //concat all columns from one table
}
$serch_jyouken = implode(" and ",$pieces_3); // for multiple keywords
$result1 = mysqli_query($connection, "select p.p_no from pfr_data p where (" .$serch_jyouken .")");
$res1 = array();
while($r1 = mysqli_fetch_array($result1){
$res1[] = $r1['p_no'] ; //fetch primary key from table and store it into array
}
foreach ($pieces_2 AS $value) {
$pieces_4[] ="(CONCAT_WS('|',$presql3) like '%$value%')"; // same as above
}
$serch_jyouken1 = implode(" and ",$pieces_4);
$result2 = mysqli_query($connection, "select p2.p_no from pfr_mod_inform p2 where (" .$serch_jyouken1 .")" );
$res2 = array();
while($r2 = mysqli_fetch_array($result2)){
$res2[] = $r2['p_no'];
}
$res_mrg = array_merge($res1 , $res2); //merge array
$result = implode("','",$res_mrg ); // array to sring
$sql5 = $presql ." from pfr_data p where p.p_no in ('$result') order by p.section_p,p.status,p.no";

need help returning sql sum of $variable table name

I'm trying to return the sum of balances from a table and can get the following code to work when using a specific table name
$qry = mysql_query("SELECT SUM(Balance) AS total FROM table1 ");
$row = mysql_fetch_assoc($qry);
echo $row['total'];
The problem I'm having is that my table name changes and this needs to be a variable but when I use the following code I get no result
$table="table1";
$qry = mysql_query(" SELECT SUM(Balance) AS total FROM $table ");
$row = mysql_fetch_assoc($qry);
echo $row['total'];
Can anyone offer some help please?
How about:
$qry = mysql_query(" SELECT SUM(Balance) AS total FROM " . $table );

PDO multiple SELECT statements

How can i do multiple select statements in one file? For example i have a list of products - i then want to get the stock level's for each of the products. However, it only ever returns the first product, not any other additional products.
$query = $db->query("SELECT * FROM `products` ORDER BY `productName` ASC");
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
$productId = stripslashes($row['productId']);
$productName = stripslashes($row['productName']);
echo "<b>".$productName."</b><br />";
$query = $db->query("SELECT * FROM `stock` WHERE `productId` = $productId");
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
$stockId = stripslashes($row['stockId']);
$stockFilename = stripslashes($row['stockFilename']);
}
echo "Stock level= " . $query-> rowCount();
}
Because your second $query is overwriting the first. Rename the second to $query2 (and change the the $query variables to $query2 beneath it). And change $row to $row2
By the way, you can also change your first query into a join to eliminate the second query alltogether.

How do I use the results of a SQL query in a subsequent query?

I want to use the result set of a query in the where statement of a subsequent query.
Running into a problem because the first query returns multiple results and I don't know how to convert these to a comma-separated string for use in an 'IN' () statement.
$Result1 = mysql_query ("
select id from Table1
where
upper('$Input') = Employee_number
")
or die(mysql_error());
$Result2 = mysql_query ("
Select * from table2 where ID in ($Result1)")
You can combine this into a single MySQL statement like this:
SELECT * FROM Table2 WHERE id IN
(SELECT id FROM Table1 where upper('$Input') = Employee_number);
But if you really want to do it like in your question, you will probably have to lookup how to work with the results from mysql_query, just look that up in a function reference.
$query1 = mysql_query("
select id from Table1
where upper('$Input') = Employee_number
") or die(mysql_error());
$ids = array();
while($Result1 = mysql_fetch_array($query1))
{
$ids[] = $Result1['id'];
}
if(sizeof($ids))
{
$n_ids = implode(',', $ids);
$query2 = mysql_query("
select * from Table2
where ID IN (" . $n_ids . ")
") or die(mysql_error());
}

select row where the slot is the biggest

i need to select one row where slot_left is the biggest. i tried
for ( $i=1;$i<3;$i++) {
$sql5 = "SELECT * from user u where (
select max(slot_left) from company c,user u
where c.id=u.company_id and c.id='$name'
)";
$result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
while($row=mysqli_fetch_array($result5)) {
// echo the id which the slot_left is the biggest
echo $i['slot_left'];
}
}
but still cannot. please help!
You have to use GROUP BY in your query.
And query execution in Loop is not recommended, it will decrees performance.
Try this.
$sql5 = "select c.id, max(slot_left) from company c,user u
where c.id=u.company_id and c.id='$id' GROUP by c.id";
$result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
while($row=mysqli_fetch_array($result5)) {
echo $row['slot_left'];
}
SQL can be. You select all rows from DB.
$sql5 = "select max(slot_left) AS slot_left from company c,user u where c.id=u.company_id and c.id='$name' GROUP by u.company_id";
$name variable used in query not set
Variable $i is not array. Array is $row
echo $row['slot_left'];

Categories