Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: mysqli problem

  1. #1
    Regular Coder
    Join Date
    May 2008
    Posts
    135
    Thanks
    13
    Thanked 10 Times in 10 Posts

    mysqli problem

    is there any reason why this wouldnt work? because i cant get it to work?

    PHP Code:
    function getAttrVals($sql){
        
    $result $db_myDB->query($sql);
        while (
    $row $result->fetch_object() ){
            
    $html .= "<option value='"$row->id ."'>"$row->name ."</option>";
        }
        
    $result->close();
        return 
    $html;

    Code:
    <select>
    <?php echo getAttrVals("SELECT * FROM products"); ?>
    </select>
    
    <select>
    <?php echo getAttrVals("SELECT * FROM products2"); ?>
    </select>
    there is a db table called products and products 2, and there are columns call id and name.

    i init the connection like so

    PHP Code:
    $db["myDB"]["host"] = "localhost";
    $db["myDB"]["user"] = "root";
    $db["myDB"]["pass"] = "xxxxxxxx";
    $db["myDB"]["db"] = "myDB";
    $db_myDB = new mysqli($db["myDB"]["host"],$db["myDB"]["user"],$db["myDB"]["pass"],$db["myDB"]["db"]); 
    for some reason it does not return anything when i run the page.

  • #2
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    You should be checking for any errors, making sure they are displaying and not being visibly obscured inside HTML tags (ie: view the output as text)... but I would venture a guess that $db_myDB is outside the function's scope:
    PHP Code:
    function getAttrVals($sql){
        global 
    $db_myDB;
        
    $html '';
        
    $result $db_myDB->query($sql);
        while (
    $row $result->fetch_object() ){
            
    $html .= "<option value='"$row->id ."'>"$row->name ."</option>";
        }
        
    $result->close();
        return 
    $html;


  • #3
    Regular Coder
    Join Date
    May 2008
    Posts
    135
    Thanks
    13
    Thanked 10 Times in 10 Posts
    oh man of course!

    that gets me everytime.

    im so use to asp, i forget about scope.

    so i pass the myslqi object to the function it works.

    is there any way of the function being able to access variables on the page, that are not session variables or declared in the scope of the function?


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •