www.webdeveloper.com
Results 1 to 10 of 10

Thread: Save information from database with PHP

  1. #1
    Join Date
    Feb 2014
    Location
    Managua, Nicaragua
    Posts
    45

    Question Save information from database with PHP

    Ok people, i dont speake english very well, so, i will explaing u my problem in spanish, and then i will use google translate service for the english version...

    /*espaņol*****/
    Tengo una funcion en PHP que se encarga de asignar valores a unas variables desde una base de datos...

    Ejemplo:
    PHP Code:
    function nombredelafuncion($key){
    $variable['key1'] = 'valor obtenido desde la base de datos';
    $variable['key2'] = 'valor obtenido desde la base de datos';
    $variable['key3'] = 'valor obtenido desde la base de datos';
    return 
    $variable[$key];

    Lo que ocurre es que si no mal entiendo, cada vez que hago uso de la funcion, la funcion se conecta a la base de datos, realiza la consulta y muestra el resultado, pero por ejemplo si utilizo esta funcion unas 7 veces por pagina, eso signica que son 7 conexiones a la base de datos y supongo es una carga pesada para la base de dato y tiende a impactar en la velocidad de carga de la pagina...

    Entonces, lo que necesito es encontrar una forma de almacenar esas variables desde la base de datos una sola vez, para que no se realicen tantas conexiones por tantas consultas generadas cada vez que utilizo la funcion...

    Espero se claro... De antemano, gracias por la ayuda...

    /*English*****/
    I have a PHP function that is responsible for assigning values ​​to the variables from a database ...

    Example:
    PHP Code:
    function nombredelafuncion($key){
    $variable['key1'] = 'valor obtenido desde la base de datos';
    $variable['key2'] = 'valor obtenido desde la base de datos';
    $variable['key3'] = 'valor obtenido desde la base de datos';
    return 
    $variable[$key];

    What happens is that if I do not misunderstand it, every time I make use of the function, the function connects to the database, executes the query and displays the result, but for example if I use this function about 7 times per page means that there are 7 connections to the database and I guess is a heavy burden on the database and tends to impact the loading speed of the page ...

    So what I need is to find a way to store these variables from the database only once, to avoid many conections by many queries generated by the many times i use the function...

    I hope I was clear ... In advance, thanks for the help ...

  2. #2
    Join Date
    Feb 2014
    Location
    Viet Nam
    Posts
    33
    - you must check connection database successfully or not?
    - that is your full source code? if have full code, we can check more.
    - you use "$variable". Did you define it as array?

  3. #3
    Join Date
    Feb 2014
    Location
    Managua, Nicaragua
    Posts
    45
    ok, this is only a quick example, for demonstration purpose...

    Obviously I make the connection to the database, verify that the data there and then I store the array...

    but, ok, here is the full code...

    PHP Code:
    function webinfo($data){
        global 
    $mysqli;
        
    $systemQuery sprintf("SELECT * FROM systeminfo LIMIT 1");
        
    $systemResultado $mysqli -> query($systemQuery);
        if(
    $systemResultado -> num_rows != 0){
            
    $systemInfo $systemResultado -> fetch_assoc();
            
    $web = array(
                
    'name' => $systemInfo['SystemName'],
                
    'description' => $systemInfo['SystemDescription'],
                
    'language' => $systemInfo['SystemLanguage'],
                
    'charset' => $systemInfo['SystemCharset'],
                
    'home' => $systemInfo['SystemHome'],
                
    'version' => $systemInfo['SystemVersion'],
                
    'owner' => $systemInfo['SystemOwner'],
                
    'ownerurl' => $systemInfo['SystemOwnerUrl'],
                
    'owneremail' => $systemInfo['SystemOwnerEmail']
            );
        }
        echo 
    $web[$data];

    then i call the function like this "webinfo('name');"

  4. #4
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    853
    Save the query results once the first time you run this as a $_SESSION variable. Then in next execution check first if the $_SESSION variable exists and use it instead of doing the query again.

  5. #5
    Join Date
    Feb 2014
    Location
    Managua, Nicaragua
    Posts
    45
    That's what I thought, but I was not sure whether to save the result in a variable $ _SESSION or some other variable or process within PHP more suitable for storing information.

  6. #6
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,537
    If the function is being called multiple time all in the same page, $_SESSION isn't necessarily needed, as that is for storing data to be available in subsequent page loads that need it (along with using session_start()) on each page.

    If session data is not needed, you could make a static variable within the function (making it about one step away from a class/object):
    PHP Code:
    function webinfo($data){
        static 
    $web;
        global 
    $mysqli// I would prefer to see this passed in as second
                        // function parameter, to avoid this dependency
        
        // only do this if we don't have data yet:
        
    if(empty($web)) {
            
    $systemQuery sprintf("SELECT * FROM systeminfo LIMIT 1");
            
    $systemResultado $mysqli -> query($systemQuery);
            if(
    $systemResultado -> num_rows != 0){
                
    $systemInfo $systemResultado -> fetch_assoc();
                
    $web = array(
                    
    'name' => $systemInfo['SystemName'],
                    
    'description' => $systemInfo['SystemDescription'],
                    
    'language' => $systemInfo['SystemLanguage'],
                    
    'charset' => $systemInfo['SystemCharset'],
                    
    'home' => $systemInfo['SystemHome'],
                    
    'version' => $systemInfo['SystemVersion'],
                    
    'owner' => $systemInfo['SystemOwner'],
                    
    'ownerurl' => $systemInfo['SystemOwnerUrl'],
                    
    'owneremail' => $systemInfo['SystemOwnerEmail']
                );
            }
        }
        echo 
    $web[$data]; // I'd prefer to see this be returned, and let the
                          // calling code decide if it should be echoed

    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  7. #7
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    853
    My impression was that the array was pretty static so a SESSION var would be perfect. Of course there is a bit of a translation problem here.....

  8. #8
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,537
    Quote Originally Posted by ginerjm View Post
    My impression was that the array was pretty static so a SESSION var would be perfect. Of course there is a bit of a translation problem here.....
    Or just a "normal" (non-super-global) array variable. All depends on whether it needs to be saved throughout a session, or just for the current script. Either one is what I'd probably opt for (well, outside of actually turning it into an object), but I was thinking using a static array within the function would make it unnecessary to change any of the other code.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  9. #9
    Join Date
    Feb 2014
    Location
    Managua, Nicaragua
    Posts
    45
    Thanks both for your help... i will work with the static var... And see what up

  10. #10
    Join Date
    Feb 2014
    Location
    south africa
    Posts
    16
    if you can call the function with all the required "sites" at once then you could do this :

    the function :
    Code:
    function webinfo(){
        global $mysqli;
        $systemQuery = sprintf("SELECT * FROM systeminfo LIMIT 1");
        $systemResultado = $mysqli -> query($systemQuery);
             
        if($systemResultado -> num_rows != 0){
            $systemInfo = $systemResultado -> fetch_assoc();
            $web = array(
                'name' => $systemInfo['SystemName'],
                'description' => $systemInfo['SystemDescription'],
                'language' => $systemInfo['SystemLanguage'],
                'charset' => $systemInfo['SystemCharset'],
                'home' => $systemInfo['SystemHome'],
                'version' => $systemInfo['SystemVersion'],
                'owner' => $systemInfo['SystemOwner'],
                'ownerurl' => $systemInfo['SystemOwnerUrl'],
                'owneremail' => $systemInfo['SystemOwnerEmail']
            );
        }else{ 
          // declare it empty, so that if no results we still get a return
          $web = array(
                'name' => '',
                'description' => '',
                'language' => '',
                'charset' => '',
                'home' => '',
                'version' => '',
                'owner' => '',
                'ownerurl' => '',
                'owneremail' => ''
            );
        }
        return $web;
    }
    the page that calls it at the top of the page :
    Code:
    $webinfoArray = webinfo();
    than when you need a setting just do this
    Code:
    $webName = $webinfoArray['name'];

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles