-1

I have problem making $dbh1 available to all php files that need it for querying. I tried using "global $dbh1" in this file where querying would run.

I have 4 files: testswitchDB3.php(main), testconnect.php, login.php and testnumcards.php

Once database is connected as run by login.php and testconnect.php. Both files are working

Thus $dbh1 is created and available by applying "global $dbh1" to testnumcards.php.

But it does not work. Following are my codes.

testswitchDB3.php

<!DOCTYPE html>
<html>
<head>
    <title>Test the switching responses between databases using buttons</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../dojo1_8/dijit/themes/soria/soria.css"/>
    <link rel="stylesheet" href="../common.css"/>
    <style type="text/css">
        html, body 
    {
            width: 100%;
            height: 100%;
            margin: 5px;
            padding: 0px;
            overflow: hidden; /* No Scrollbar */
        }
    </style>
    <script>            
    var dojoConfig =
        {
              parseOnLoad: true,
              isDebug: true,
              async: true,//
              locale : "en-us"//
        }; 
    </script>
    <script src='../dojo1_8/dojo/dojo.js'></script>
</head>

<body class="soria">
<div id="main_bContainer" data-dojo-type="dijit.layout.BorderContainer" data-dojo-props="design:'sidebar'">
<div id="cp_Center" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center'">
<table>
    <tr>
     <td>
      <div id=btn1></div><!--for testdata2060_03-->
     </td>
     <td>
      <div id=btn2></div><!--for testdata2060_10-->
     </td>
     <td>
      <div id=btn3></div><!--for testdata2060_05-->
     </td>
    </tr>
    <tr>
     <td>
      <div id=btn4></div><!--for testdata2060_03-->
     </td>
     <td>
      <div id=btn5></div><!--for testdata2060_10-->
     </td>
     <td>
      <div id=btn6></div><!--for testdata2060_05-->
     </td>
    </tr>
    <tr>
     <td>
      <div id=btn7></div><!--for testdata2060_03-->
     </td>
     <td>
      <div id=btn8></div><!--for testdata2060_10-->
     </td>
     <td>
      <div id=btn9></div><!--for testdata2060_05-->
     </td>
    </tr>
 </table>
<div id=statement></div>
</div><!--cp_Center-->
</div><!--main_bContainer-->

<script>
    require(["dojo/parser", "dijit/layout/BorderContainer", "dijit/form/Button",
    "dojo/on", "dijit/form/Select", "dojo/store/Memory", "dojo/request", 
    "dojo/dom", "dojo/dom-construct", "dojo/domReady!"],
    function(parser, BorderContainer, Button, on, Select, Memory, request, dom, 
    domConstruct)
    {var commonDB = "nameless"; function connect(commonDB)
        {request.post("testconnect.php",
            {data:{nameDB : commonDB}
            //,handleAs:"json"//without the use of "handleAs:JSON" as it needs only 
            confirnation or not 
             }).then
        (function(connect)
            {console.debug("data read as: ", connect);
    if(connect)//as true or false as indicated in login.php 
            {alert("Successfully login and connected");
            switch(commonDB)
                {
                 case 'testdata2060_03':
                    btn4.set('disabled', false);
                    btn5.set('disabled', true);
                    btn6.set('disabled', true);
                    btn7.set('disabled', false);
                    btn8.set('disabled', true);
                    btn9.set('disabled', true);
                    break;
                 case 'testdata1970_11':
                    btn4.set('disabled', true);
                    btn5.set('disabled', false);
                    btn6.set('disabled', true);
                    btn7.set('disabled', true);
                    btn8.set('disabled', false);
                    btn9.set('disabled', true);
                    break;
                 case 'testdata1970_05':
                    btn4.set('disabled', true);
                    btn5.set('disabled', true);
                    btn6.set('disabled', false);
                    btn7.set('disabled', true);
                    btn8.set('disabled', true);
                    btn9.set('disabled', false);
                    break;
                }}  
             else
                alert("Attempt to login and connect is NOT successful");
                },


            (
              function(error)
                {
                    alert("Test's Error:"+error);
                    console.debug(error);
                }
        );
       }

       function card(commonDB)
        {request.post("testnumcards.php",
          {
          //{data:{xxx:yyy},
           handleAs: "json"
          }).then
         (function(response)
             {alert("The number of the distinct catds for "+commonDB+" is "+response);
               dom.byId("statement").innerHTML = "The number of the distinct catds for
               "+commonDB+" is "+response;
              },
          function(error)
              {alert("Test's Error:"+error);
               console.debug(error);
              }
         )}

/*
function test()
{
}
*/

var btn1 = new Button // Button, not button
({  label: "testdata2060_03",
    onClick: function()
     {
         console.log("Console Log: Button1 has been clicked.");
         connect('testdata2060_03');
     }
 },"btn1"); 
btn1.startup();

var btn2 = new Button
({label: "testdata1970_11"
 },"btn2");
btn2.startup();

var btn3 = new Button
({label: "testdata1970_05"
  },"btn3");
btn3.startup();

var btn4 = new Button // Button, not button
({label: "Number of cards",
    disabled: true
 },"btn4"); 
btn4.startup();

var btn5 = new Button
({label: "Number of cards",
    disabled: true
 },"btn5");
btn5.startup();

var btn6 = new Button
({label: "Number of cards",
    disabled: true
 },"btn6");
btn6.startup();

var btn7 = new Button // Button, not button
({label: "Number of tests",
    disabled: true
 },"btn7"); 
btn7.startup();

var btn8 = new Button
({label: "Number of tests",
   disabled: true
},"btn8");
btn8.startup();

var btn9 = new Button
({label: "Number of tests",
   disabled: true
},"btn9");
btn9.startup();

/*on(btn1, 'click', function()
{console.log("Console Log: Button1 has been clicked.");
 connect('testdata2060_03');
});
*/

on(btn2, 'click', function()
{console.log("Console Log: Button2 has been clicked.");
connect('testdata1970_11');
});

on(btn3, 'click', function()
{console.log("Console Log: Button3 has been clicked.");
connect('testdata1970_05');
});

on(btn4, 'click', function()
{console.log ("Console Log: Button4 has been clicked.");
card();
});

on(btn5, 'click', function()
{console.log("Console Log: Button5 has been clicked.");
test();
});

on(btn6, 'click', function()
{console.log("Console Log: Button6 has been clicked.");
card();
});

on(btn7, 'click', function()
{console.log("Console Log: Button7 has been clicked.");
test();
});

on(btn8, 'click', function()
{console.log("Console Log: Button8 has been clicked.");
card();
});

on(btn9, 'click', function()
{console.log("Console Log: Button9 has been clicked.");
test();
});

});
</script>
</body>

Next is testconnect.php

<?php
global $dbh1;
$dbname = $_POST['nameDB']; 
require_once '../scripts/login.php';
echo $connect;
?>

Next is login.php

<?php
    global $dbname;
    global $dbh1;

    $dbh1 =  null; 
    $dsn ="mysql:host=localhost; dbname=$dbname";
    $user ='root';
    $pswd ='';

 try
    {
     $dbh1 = new PDO($dsn, $user, $pswd, array(PDO::ATTR_TIMEOUT => "10",// 10 seconds
     PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); // connect to DB, declared as global variable!
     $connect = TRUE;
    }

catch(PDOException $err)
    {
     $alertmsg = $err->getMessage();
     $connect = FALSE;
    }

echo $connect;      
?>

Next is testnumcards.php

<?php
 global $dbh1;

 $stmt = $dbh1->prepare("select count(distinct mfg_code)as mfg_code from test");

 try
  {
    $stmt->execute();
  }

catch(PDOException $err)
 {
   $alertmsg = $err->getMessage();
 }

$num = $stmt->fetch(PDO::FETCH_ASSOC);
echo $num['mfg_code'];

?>

You can refer to JsFiddle for your reference though it cannot be used without PHP support.

r5d
  • 579
  • 5
  • 24
user1739825
  • 820
  • 4
  • 10
  • 27

1 Answers1

1

You need to start your files with

<?php
require("login.php"); 

in all of your php scripts for them to be able to use a connection unless those scripts have already been include or required that file.

The connection has to be created every request as when a request ends, the connection is closed. so when you request testnumcards.php there is no $dbh1 to declare global as it has not been set up on that request

EDIT

PHP is a request specific language every time you send a new request to the server it needs to create connections again and set up variables, one page has no knowledge of resources that were created in another page as all resources are closed between requests.

So if I go to page1.php and connect to a database, when I later go to page2.php it has no connection to the database unless I create that connection again. When page1.php has finished and then the connection is closed, You then need to connect again in page2.php

This is why most scripts start by requiring a file that sets up any connections or other resources they need

Anigel
  • 3,435
  • 1
  • 17
  • 23
  • require in every php file? I thought that $dbh has been created and it can be used every time query is used? I am confused already... – user1739825 Jul 23 '13 at 09:54
  • $dbh was closed as soon as the first page finished loading. It only exists for the duration of that page and needs to be recreated when the next page is loaded. NB a page is not necessarily a file, but it is any page that is directly requested by an end user – Anigel Jul 23 '13 at 09:58
  • Anigel is totally right, but I see you've used global like I suggested (http://stackoverflow.com/questions/17800297/maintain-dbh-database-handle-across-all-php-files/17800359?noredirect=1#comment25981214_17800359). Remember, as soon as the page is loaded, the PHP script dies and ALL variables are lost: this unfortunately includes the connection to the database. But, rather than use `require`, I'd use `require_once`. This way, if you have many PHP files that all use the same database PHP file, the database will only be loaded once. – AStupidNoob Jul 23 '13 at 10:14
  • Hi all thanks. How about PHP's session? Will this also work? – user1739825 Jul 25 '13 at 06:13
  • No that wouldn't work for a resource. it will only work for data. see http://stackoverflow.com/questions/6078843/storing-database-connection-in-a-session-variable – Anigel Jul 25 '13 at 08:00
  • @Anigel If in login.php, I changed to "$dbh1 = new PDO($dsn, $user, $pswd, array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));", maybe that will work, as it will keep connection persistent. But it does not work. So I added in testnumcards.php :- "$dbname = $_POST['nameDB']; require '../scripts/login.php';" Then error result stated that nothing for $dbname is captured in testnumcards.php althought the same code is successful in testconnect.php. I am getting vexed. Perhaps You can point me to some examples. I am using PDO. – user1739825 Jul 26 '13 at 09:13
  • I can't give you some examples for things that do not exist. Try reconnecting each new request and it will work. – Anigel Jul 26 '13 at 09:15
  • @Anigel Hi. Turns out that in testswitchDb3.php, commonDB is not defined!I am so slow to analysing the errors and bugs. Thanks. By right all the codes in the other php files should be working... Thanks. Now trying to find out what went wrong with this code "function card(commonDB)" – user1739825 Jul 26 '13 at 09:21
  • Finally it is solved. The reason it was not defined , is because I forgot to add value to the parameter in the function. But it's messy and now I understand how it should work. Gotta clean up. many thanks to all of you... – user1739825 Jul 26 '13 at 09:50