get required result in sql - php

i have a sql database having two columns
1. id and 2. parent_id
i want to select all ids where parent_id=1 [let the results saved in X array] then,
select all the ids where parent_id in X[] [let the results saved in Y array] then... do the same upto 7 levels at last i want to sum all levels and get that sum in a variable name "number"
what i tried:
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id = ".$parent[id];
$result = mysqli_query($con, $sql);
$lv1 = mysqli_fetch_array($result);
then again
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id in ($lv1)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
and so on.... it may give me required result but it is too much code...
i want to the same by using a loop or something else... to shorten the code.

Your first query gets count(id) and then second query uses it to get results. It seems you have many flaws in your requirement to begin with.
However, for your question you can use sub-query like following
$sql = "SELECT count(id) as leadersearch
FROM `$database`.`$mem`
WHERE parent_id in (
SELECT id FROM `$database`.`$mem` where parent_id = ".$parent['id']."
)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
If you have many level nesting and you want to search records like this then you can consider functions:
function getLeader($parent_id){
$results = [];
$sql = "SELECT id as leadersearch FROM `$database`.`$mem` where parent_id in (".$parent_id.")";
$result = mysqli_query($con, $sql);
foreach($row = mysqli_fetch_array($result)){
$results[] = $row['id'];
}
return $results;
}
$leaders = [];
$ids = getLeader($parent['id']);
foreach($ids as $id){
$leaders[$id] = getLeader($id);
}

Related

Get values from different tables inside a while loop statement using php

I'm having an issue of retrieving values from two different tables. Here's the code so far:
$result = mysqli_query($conn,"SELECT * FROM articles");
$num = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
$uid=$row['_uid'];
$result2 = mysqli_query($conn, "SELECT _username FROM users WHERE _id = '$uid' ";
$num2 = mysqli_num_rows($result2);
while ($row2 = mysqli_fetch_array($result2)) {
$username = $row2['_username'];
}
$divtext='<h3>'.$row['_posttype'].'</h3> <h2>'.$username.' </h2>';
}
I've been reading that I should preform this while inside a while with multiple query, also found on w3 that you could directly assign a value to a variable directly using:
"SELECT _username INTO $username FROM users WHERE _id = '$uid' LIMIT 1";
But this works in SQL inside myadmin, in a php I can't find how to cast it.
I have also replace the fetch_row for fetch_assoc and still nothing, im struggling for two days already with this.
you could select al the value using a single query
SELECT a._uid , a._posttype, u._username
FROM articles a
INNER JOIN users u on a._uid = u._id
..
$result = mysqli_query($conn,
"SELECT a._uid , a._posttype, u._username
FROM articles a
INNER JOIN users u on a._uid = u._id");
$num = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
$divtext='<h3>'.$row['_posttype'].'</h3> <h2>'.$username.' </h2>';
}
$echo $divtext;

MySQL: Get all Columns of Table starting with name "ctr_" and value 1

I have a country restriction on products in my shop and a slow query to select all country-columns with a value of 1 from the table product.
I select all active countries in my shop:
$ids = select id from country where active = 1;
Then I select all countries, which are active in a product:
foreach $ids as $id { select ctr_{$id} from product where ctr_{$id} = 1;
Is there a faster way to get the columns starting with ctr_* and which value is equal to 1?
Try the following
// first get the columns
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='product' AND COLUMN_NAME LIKE 'ctr_%'";
$result = mysqli_query($conn, $query) or trigger_error(mysqli_error($conn),E_USER_ERROR);
$cols = Array();
while($row = mysqli_fetch_row($result)) $cols[] = $row[0];
// then build the query
if(count($cols))
{
$query = 'SELECT '.implode(',', $cols).' FROM product WHERE 1 IN ('.implode(',',$cols).')';
$result = mysqli_query($conn, $query) or trigger_error(mysqli_error($conn), E_USER_ERROR);
while($row = mysqli_fetch_assoc($conn,$result))
{
// do something with the row
// ....
}
}

Displaying Row Count for Data in PHP

Been at this awhile...this is actually another simplified question to a problem I posted earlier. I'm trying to display the country and count for the following query:
$query = mysqli_query($con, "SELECT COUNT(id), country FROM users GROUP BY country ORDER BY COUNT(id) DESC");
while ($row = mysqli_fetch_array($query)) {
$countries = $row['country'];
echo $countries;}
What I'm getting in output is the countries listed from highest to lowest, but it does not have the count displayed next to it. I know these have been summed in the query, how do I target the number & assign it to a php variable for display?
Any help would be appreciated.
You can use an alias for your COUNT column and then reference that in the array returned by mysqli_fetch_array for each row.
$query = mysqli_query($con, "SELECT COUNT(id) AS countryCount, country FROM users GROUP BY countryCount ORDER BY countryCount DESC");
while ($row = mysqli_fetch_array($query)) {
$count = $row['countryCount'];
$countries = $row['country'];
echo $count;
echo $countries;}
You need to add alias in query for COUNT(id) like below:-
$query = mysqli_query($con, "SELECT COUNT(id) as count, country FROM users GROUP BY country ORDER BY count DESC");
Now change while() loop code a bit:-
while ($row = mysqli_fetch_assoc($query)) { // _assoc for lighter array iteration
$countries = $row['country'];
$countries_count = $row['count'];// get count of each country
echo $countries.'--'.$countries_count ;// show country and it's count both
}
Is this what you are trying to do:-
$query = mysqli_query($con, "SELECT COUNT(id) AS total_country, country FROM users GROUP BY country ORDER BY id DESC");
while ( $row = mysqli_fetch_array( $query ) )
{
$countries = $row['country'];
$total_countries = $row['total_country'];
echo "<p>{$countries}</p>;
echo "<p>Total count: {$total_countries}</p>";
}
You're not assigning the variable.
Do this: $count = $row['COUNT']; and echo it. It should work

Query inside while loop repeats results from 2 tables

I am not sure if the title expresses the problem accurately or not. Anyways, here is the explanation:
I have 2 tables, the first one holds users IDs, the other one holds their posts.
The fist query selects user IDs from the fist table, and it loop through the second table to find the users (IDs) posts.
The problem is that when the query finds eg. 5 results (user IDs 1, 6, 999.. etc) in the fist table, then it loops 5 times to search in the second table, it shows 5 results even if the real results is 2 post only created by user 1 and 6.
How can I avoid this repeatation?
Here is the code:
$stmt = $conn->prepare('select userid from table where para=?');
$stmt->bind_param('i', $para);
$stmt->execute();
$result = $stmt->get_result();
while( $row = $result->fetch_assoc()) {
$userid = $row["userid "];
$qname = "select postid,title from posts where uid='$userid'";
$result2 = $conn->query($qname);
$row2 = $result2->fetch_array(MYSQLI_ASSOC);
if ($row2 > 0) {
$postid= $row2['postid'];
$title= $row2['title'];
}
echo $postid." ".$title."<br>";
}
Try
$qname = "select postid,title from posts as P left join table as T on T.userid=P.uid where where para=?";
Or
You can store the results in a common array during the loop.
like
$tempResult = array();
while( $row = $result->fetch_assoc()) {
$userid = $row["userid "];
$qname = "select postid,title from posts where uid='$userid'";
$result2 = $conn->query($qname);
$row2 = $result2->fetch_array(MYSQLI_ASSOC);
if ($row2 > 0) {
$tempResult[$userid][] = $row2['postid'];
$tempResult[$userid][] = $row2['title'];
}
}
you can try this query using a JOIN MYSQL.
SELECT u.userid,p.postid,p.title FROM TABLE `user` u
JOIN posts p ON
p.uid = u.userid
WHERE para=?
You can avoid it by only running one query that joins the two tables together. Something like this:
<?php
$stmt = $conn->prepare('select posts.* from table t inner join posts p on t.userid = p.uid where t.para = ? order by uid');
$stmt->bind_param('i', $para);
$stmt->execute();
$result = $stmt->get_result();
while( $row = $result->fetch_assoc()) {
// $row now has userid, and all post details
}
?>

how can i controll while loop into another while loop

Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);

Categories