使用全局数据库连接不起作用

时间:2015-07-20 11:54:02

标签: php

确定。大家好。

我的数据库连接存在一些问题,并在php中使用它。

我的普通文件结构:

db.php中

SELECT CASE when rn = 1 THEN CAST(ID AS VARCHAR(8)) ELSE '' END AS ID, 
       CASE when rn = 1 THEN Name ELSE '' END AS Name, 
       [Jan], [Feb], [Mar]      
FROM (
   SELECT ID, Name, Val, Mon,
          ROW_NUMBER() OVER (PARTITION BY ID, Name, Mon ORDER BY val) AS rn
   FROM (
      SELECT ID, Name, Jan, Feb, Mar
      FROM mytable ) p
   UNPIVOT 
      (Val FOR Mon IN (Jan, Feb, Mar) ) AS unpvt
) src
PIVOT (
   MAX(Val) FOR Mon IN ([Jan], [Feb], [Mar]) ) AS pvt 

functions.php文件

$mysql_server   = "server";
$mysql_user     = "user";
$mysql_password = "password";
$mysql_db       = "name";

$db = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
if ($db->connect_errno) {
    exit();
}
$db->set_charset("utf8");

我100%确定用户的凭据是否正常,所以这不是问题。

你能给我一些建议吗?我在每个项目中使用了这个结构,现在我正在试图弄明白我的想法。我打赌是我错过的东西!

请帮忙!谢谢!

1 个答案:

答案 0 :(得分:0)

尝试使用以下代码!!!

<?php
$mysql_server  = "localhost";
$mysql_user    = "root";
$mysql_password = "";
$mysql_db      = "dbName";

$db = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
if ($db->connect_errno)
{
    exit();
}
$db->set_charset("utf8");


function func_name() {
  global $db;
  $sql = "SELECT text FROM tableName";
  $result = $db->query($sql);

  if ($result->num_rows > 0) {

    while ($row = $result->fetch_assoc()) {
      echo $row["columnName"];
    }
  } else {
    echo "0 results";
  }
}

func_name();
mysqli_close($db);
?>