Changing code from an while loop to array_shiftDeleting an element from an array in PHPSubcategories MySql and phpHow do I get a YouTube video thumbnail from the YouTube API?Selecting min idReference - What does this error mean in PHP?Using <option> to get ID and post it in another queryhow to get path of linked categories in MysqlWhile inside while inside whileUnable to connect my sql server from PHPHow to Optimize COUNT() when using in Large Loop

What are these things that surround museum exhibits called?

Real mode flat model

2000s space film where an alien species has almost wiped out the human race in a war

I was promised a work PC but still awaiting approval 3 months later so using my own laptop - Is it fair to ask employer for laptop insurance?

Permutations in Disguise

Read string of any length in C

How do I create indestructible terrain?

geschafft or geschaffen? which one is past participle of schaffen?

Some Prime Peerage

How to give my students a straightedge instead of a ruler

How to write characters doing illogical things in a believable way?

How To Make Earth's Oceans as Brackish as Lyr's

Telling my mother that I have anorexia without panicking her

In what sequence should an advanced civilization teach technology to medieval society to maximize rate of adoption?

What is the mathematical notation for rounding a given number to the nearest integer?

Usage of blank space in trade banner and text-positioning

Where is it? - The Google Earth Challenge Ep. 2

Does a succubus' charm end when it dies?

Does my opponent need to prove his creature has morph?

Output a Super Mario Image

Absolutely wonderful numerical phenomenon. Who can explain?

What makes a smart phone "kosher"?

What was the ultimate objective of The Party in 1984?

Are there successful ways of getting out of a REVERSE MORTGAGE?



Changing code from an while loop to array_shift


Deleting an element from an array in PHPSubcategories MySql and phpHow do I get a YouTube video thumbnail from the YouTube API?Selecting min idReference - What does this error mean in PHP?Using <option> to get ID and post it in another queryhow to get path of linked categories in MysqlWhile inside while inside whileUnable to connect my sql server from PHPHow to Optimize COUNT() when using in Large Loop






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have a DB with categories and subcategories and I want to find the original parent of a subcategory. For example if I have C1->C2->C3->C4 where C1 is the original parent, I want to find the id of C1, knowing the id of C4. I have succeded to find it using an if statement with a while loop but I was told to change it to a array_shift() because the while would be very slow when there will be a lot of data going through it. The problem is that I cannot figure out how to change the code from while to array_shift, not even where to start. This is what I have right now:



 $sql = "SELECT `parent_id` FROM c_assoc WHERE c_id = $cToPutInto";
$result = $conn -> query($sql);

if($result -> num_rows > 0)
$parent = $result -> fetch_assoc()['parent_id'];
$sql = "SELECT `parent_id` FROM c_assoc WHERE c_id = $parent";
$result = $conn -> query($sql);
while ($result -> num_rows > 0)
$parent = $result -> fetch_assoc()['parent_id'];
$sql = "SELECT `parent_id` FROM c_assoc WHERE c_id = $parent";
$result = $conn -> query($sql);











share|improve this question
























  • Is $con a PDO object here?

    – Simon Brahan
    Mar 28 at 11:27











  • if i understand , your code work fine with the while loop , is that true ?

    – Mohammed Yassine CHABLI
    Mar 28 at 11:38











  • @MohammedYassineCHABLI, yes it does!

    – fullstackwannabe
    Mar 28 at 11:39











  • @SimonBrahan, I am using MySQLi Object-Oriented. $conn comes from where I create the connection.

    – fullstackwannabe
    Mar 28 at 11:41











  • if you want , you can use Recursive CTE , it like a recursive query , at the end , you will have the final parent . wanna some example ?

    – Mohammed Yassine CHABLI
    Mar 28 at 11:43

















0















I have a DB with categories and subcategories and I want to find the original parent of a subcategory. For example if I have C1->C2->C3->C4 where C1 is the original parent, I want to find the id of C1, knowing the id of C4. I have succeded to find it using an if statement with a while loop but I was told to change it to a array_shift() because the while would be very slow when there will be a lot of data going through it. The problem is that I cannot figure out how to change the code from while to array_shift, not even where to start. This is what I have right now:



 $sql = "SELECT `parent_id` FROM c_assoc WHERE c_id = $cToPutInto";
$result = $conn -> query($sql);

if($result -> num_rows > 0)
$parent = $result -> fetch_assoc()['parent_id'];
$sql = "SELECT `parent_id` FROM c_assoc WHERE c_id = $parent";
$result = $conn -> query($sql);
while ($result -> num_rows > 0)
$parent = $result -> fetch_assoc()['parent_id'];
$sql = "SELECT `parent_id` FROM c_assoc WHERE c_id = $parent";
$result = $conn -> query($sql);











share|improve this question
























  • Is $con a PDO object here?

    – Simon Brahan
    Mar 28 at 11:27











  • if i understand , your code work fine with the while loop , is that true ?

    – Mohammed Yassine CHABLI
    Mar 28 at 11:38











  • @MohammedYassineCHABLI, yes it does!

    – fullstackwannabe
    Mar 28 at 11:39











  • @SimonBrahan, I am using MySQLi Object-Oriented. $conn comes from where I create the connection.

    – fullstackwannabe
    Mar 28 at 11:41











  • if you want , you can use Recursive CTE , it like a recursive query , at the end , you will have the final parent . wanna some example ?

    – Mohammed Yassine CHABLI
    Mar 28 at 11:43













0












0








0








I have a DB with categories and subcategories and I want to find the original parent of a subcategory. For example if I have C1->C2->C3->C4 where C1 is the original parent, I want to find the id of C1, knowing the id of C4. I have succeded to find it using an if statement with a while loop but I was told to change it to a array_shift() because the while would be very slow when there will be a lot of data going through it. The problem is that I cannot figure out how to change the code from while to array_shift, not even where to start. This is what I have right now:



 $sql = "SELECT `parent_id` FROM c_assoc WHERE c_id = $cToPutInto";
$result = $conn -> query($sql);

if($result -> num_rows > 0)
$parent = $result -> fetch_assoc()['parent_id'];
$sql = "SELECT `parent_id` FROM c_assoc WHERE c_id = $parent";
$result = $conn -> query($sql);
while ($result -> num_rows > 0)
$parent = $result -> fetch_assoc()['parent_id'];
$sql = "SELECT `parent_id` FROM c_assoc WHERE c_id = $parent";
$result = $conn -> query($sql);











share|improve this question














I have a DB with categories and subcategories and I want to find the original parent of a subcategory. For example if I have C1->C2->C3->C4 where C1 is the original parent, I want to find the id of C1, knowing the id of C4. I have succeded to find it using an if statement with a while loop but I was told to change it to a array_shift() because the while would be very slow when there will be a lot of data going through it. The problem is that I cannot figure out how to change the code from while to array_shift, not even where to start. This is what I have right now:



 $sql = "SELECT `parent_id` FROM c_assoc WHERE c_id = $cToPutInto";
$result = $conn -> query($sql);

if($result -> num_rows > 0)
$parent = $result -> fetch_assoc()['parent_id'];
$sql = "SELECT `parent_id` FROM c_assoc WHERE c_id = $parent";
$result = $conn -> query($sql);
while ($result -> num_rows > 0)
$parent = $result -> fetch_assoc()['parent_id'];
$sql = "SELECT `parent_id` FROM c_assoc WHERE c_id = $parent";
$result = $conn -> query($sql);








php






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 28 at 11:16









fullstackwannabefullstackwannabe

53 bronze badges




53 bronze badges















  • Is $con a PDO object here?

    – Simon Brahan
    Mar 28 at 11:27











  • if i understand , your code work fine with the while loop , is that true ?

    – Mohammed Yassine CHABLI
    Mar 28 at 11:38











  • @MohammedYassineCHABLI, yes it does!

    – fullstackwannabe
    Mar 28 at 11:39











  • @SimonBrahan, I am using MySQLi Object-Oriented. $conn comes from where I create the connection.

    – fullstackwannabe
    Mar 28 at 11:41











  • if you want , you can use Recursive CTE , it like a recursive query , at the end , you will have the final parent . wanna some example ?

    – Mohammed Yassine CHABLI
    Mar 28 at 11:43

















  • Is $con a PDO object here?

    – Simon Brahan
    Mar 28 at 11:27











  • if i understand , your code work fine with the while loop , is that true ?

    – Mohammed Yassine CHABLI
    Mar 28 at 11:38











  • @MohammedYassineCHABLI, yes it does!

    – fullstackwannabe
    Mar 28 at 11:39











  • @SimonBrahan, I am using MySQLi Object-Oriented. $conn comes from where I create the connection.

    – fullstackwannabe
    Mar 28 at 11:41











  • if you want , you can use Recursive CTE , it like a recursive query , at the end , you will have the final parent . wanna some example ?

    – Mohammed Yassine CHABLI
    Mar 28 at 11:43
















Is $con a PDO object here?

– Simon Brahan
Mar 28 at 11:27





Is $con a PDO object here?

– Simon Brahan
Mar 28 at 11:27













if i understand , your code work fine with the while loop , is that true ?

– Mohammed Yassine CHABLI
Mar 28 at 11:38





if i understand , your code work fine with the while loop , is that true ?

– Mohammed Yassine CHABLI
Mar 28 at 11:38













@MohammedYassineCHABLI, yes it does!

– fullstackwannabe
Mar 28 at 11:39





@MohammedYassineCHABLI, yes it does!

– fullstackwannabe
Mar 28 at 11:39













@SimonBrahan, I am using MySQLi Object-Oriented. $conn comes from where I create the connection.

– fullstackwannabe
Mar 28 at 11:41





@SimonBrahan, I am using MySQLi Object-Oriented. $conn comes from where I create the connection.

– fullstackwannabe
Mar 28 at 11:41













if you want , you can use Recursive CTE , it like a recursive query , at the end , you will have the final parent . wanna some example ?

– Mohammed Yassine CHABLI
Mar 28 at 11:43





if you want , you can use Recursive CTE , it like a recursive query , at the end , you will have the final parent . wanna some example ?

– Mohammed Yassine CHABLI
Mar 28 at 11:43












1 Answer
1






active

oldest

votes


















0
















Here is a simple example that you can try :



Let's suppose you have a table categorie like :



 "id"|"parent_id"|"name"
"1" | NULL | "PHP"
"2" | "1" |"Symfony"
"3" | "1" |"Laravel"
"4" | NULL |"JAVA"
"5" | "4" |"Spring"
"6" | "4" |"JEE"
"7" | "2" |"Command"
"8" | "2" |"Request"


the root parent categorie has parent_id equal to null , so you can mae a simple query to select the root parent without making while loop , like :



select * from (select name, id, @parent:=parent_id as parent from 
(select @parent:=8 ) a join (select * from categorie order by id desc) b
where @parent=id) as res WHERE res.parent IS NULL


In your can , you can inject the id of the categorie you want (in my example , i'm using 8 value )



The result return :



|id|name|parent|
| | | |
|1 |PHP | NULL |


Hope that help you.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );














    draft saved

    draft discarded
















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55396241%2fchanging-code-from-an-while-loop-to-array-shift%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0
















    Here is a simple example that you can try :



    Let's suppose you have a table categorie like :



     "id"|"parent_id"|"name"
    "1" | NULL | "PHP"
    "2" | "1" |"Symfony"
    "3" | "1" |"Laravel"
    "4" | NULL |"JAVA"
    "5" | "4" |"Spring"
    "6" | "4" |"JEE"
    "7" | "2" |"Command"
    "8" | "2" |"Request"


    the root parent categorie has parent_id equal to null , so you can mae a simple query to select the root parent without making while loop , like :



    select * from (select name, id, @parent:=parent_id as parent from 
    (select @parent:=8 ) a join (select * from categorie order by id desc) b
    where @parent=id) as res WHERE res.parent IS NULL


    In your can , you can inject the id of the categorie you want (in my example , i'm using 8 value )



    The result return :



    |id|name|parent|
    | | | |
    |1 |PHP | NULL |


    Hope that help you.






    share|improve this answer





























      0
















      Here is a simple example that you can try :



      Let's suppose you have a table categorie like :



       "id"|"parent_id"|"name"
      "1" | NULL | "PHP"
      "2" | "1" |"Symfony"
      "3" | "1" |"Laravel"
      "4" | NULL |"JAVA"
      "5" | "4" |"Spring"
      "6" | "4" |"JEE"
      "7" | "2" |"Command"
      "8" | "2" |"Request"


      the root parent categorie has parent_id equal to null , so you can mae a simple query to select the root parent without making while loop , like :



      select * from (select name, id, @parent:=parent_id as parent from 
      (select @parent:=8 ) a join (select * from categorie order by id desc) b
      where @parent=id) as res WHERE res.parent IS NULL


      In your can , you can inject the id of the categorie you want (in my example , i'm using 8 value )



      The result return :



      |id|name|parent|
      | | | |
      |1 |PHP | NULL |


      Hope that help you.






      share|improve this answer



























        0














        0










        0









        Here is a simple example that you can try :



        Let's suppose you have a table categorie like :



         "id"|"parent_id"|"name"
        "1" | NULL | "PHP"
        "2" | "1" |"Symfony"
        "3" | "1" |"Laravel"
        "4" | NULL |"JAVA"
        "5" | "4" |"Spring"
        "6" | "4" |"JEE"
        "7" | "2" |"Command"
        "8" | "2" |"Request"


        the root parent categorie has parent_id equal to null , so you can mae a simple query to select the root parent without making while loop , like :



        select * from (select name, id, @parent:=parent_id as parent from 
        (select @parent:=8 ) a join (select * from categorie order by id desc) b
        where @parent=id) as res WHERE res.parent IS NULL


        In your can , you can inject the id of the categorie you want (in my example , i'm using 8 value )



        The result return :



        |id|name|parent|
        | | | |
        |1 |PHP | NULL |


        Hope that help you.






        share|improve this answer













        Here is a simple example that you can try :



        Let's suppose you have a table categorie like :



         "id"|"parent_id"|"name"
        "1" | NULL | "PHP"
        "2" | "1" |"Symfony"
        "3" | "1" |"Laravel"
        "4" | NULL |"JAVA"
        "5" | "4" |"Spring"
        "6" | "4" |"JEE"
        "7" | "2" |"Command"
        "8" | "2" |"Request"


        the root parent categorie has parent_id equal to null , so you can mae a simple query to select the root parent without making while loop , like :



        select * from (select name, id, @parent:=parent_id as parent from 
        (select @parent:=8 ) a join (select * from categorie order by id desc) b
        where @parent=id) as res WHERE res.parent IS NULL


        In your can , you can inject the id of the categorie you want (in my example , i'm using 8 value )



        The result return :



        |id|name|parent|
        | | | |
        |1 |PHP | NULL |


        Hope that help you.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 28 at 13:37









        Mohammed Yassine CHABLIMohammed Yassine CHABLI

        1,6122 gold badges7 silver badges31 bronze badges




        1,6122 gold badges7 silver badges31 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.




















            draft saved

            draft discarded















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55396241%2fchanging-code-from-an-while-loop-to-array-shift%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript