MySQL数据库无法连接

时间:2015-07-24 19:42:30

标签: php mysql

我将一个看似简单的数据库连接功能从一个文件复制到另一个文件,现在它不起作用。这让我有点生气:

<?php
//connect-to-database
function database_connect(){
    $username="test";
    $password="password123";
    $hostname="xxx.xxx.xxx.xxx";
    $db_name="database";        
    //connection to the database
    $dbhandle = mysqli_connect($hostname, $username, $password,$db_name) or die ("Unable to connect to MySQL");
    return $dbhandle;       
}
function get_row($id){
global $db;
$query = "SELECT * FROM users WHERE userID='".$id."'";
$result = mysqli_query($db, $query);
  if (mysqli_num_rows($result) > 0) {
     // create a variable for each item
     $row = mysqli_fetch_object($result);
     $first = $row->first;
     $last  = $row->last;
     $email = $row->email;
{    

$db = database_connect();
get_row(1); //get a test user with id of 1
echo "Hello".$first;

2 个答案:

答案 0 :(得分:1)

在你的代码中,你没有将dbhandle设置为变量,也没有连接get_row函数。为了减少过多的连接,我建议将dbhandle存储为变量,并使用全局范围在get_row中访问它。

所以你的代码应该是这样的

<?php
//connect-to-database
function database_connect(){
    $username="test";
    $password="password123";
    $hostname="xxx.xxx.xxx.xxx";
    $db_name="database";        
    //connection to the database
    $dbhandle = mysqli_connect($hostname, $username, $password,$db_name) or die ("Unable to connect to MySQL");
    return $dbhandle;       
}

function get_row($id){
global $db;
$query = "SELECT * FROM users WHERE userID='".$id."'";
$result = mysqli_query($db, $query);
   if (mysqli_num_rows($result) > 0) {
     $row = mysqli_fetch_object($result);
     // create a variable for each item
     return $row;
   }
   else{
     return false;
   }
}    

$db = database_connect();
$row = get_row(1); //get a test user with id of 1
$first = $row->first;
$last  = $row->last;
$email = $row->email;

echo "Hello".$first;

答案 1 :(得分:-1)

<?php
//connect-to-database
function database_connect(){
$username="test";
$password="password123";
$hostname="xxx.xxx.xxx.xxx";
$db_name="database";        
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password,$db_name) or die ("Unable to connect to MySQL");
return $dbhandle;       
}
function get_row($id){
$query = "SELECT * FROM users WHERE userID='".$get_row($id)."'";
$row = mysqli_query($dbhandle, $query);
  if (mysqli_num_rows($row) > 0) {
 // create a variable for each item
 $first = $row->first;
 $last  = $row->last;
 $email = $row->email;
{    

database_connect();
get_row(1); //get a test user with id of 1
echo "Hello".$first;