MySQL数据库无法连接[关闭]
问题描述:
I copied a seemingly simple database connect function from one file to another and now it won't work. It's driving me a little mad:
<?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;
答
In your code you dont have dbhandle set as a variable neither connect inside get_row function. To reduce excessive connections I would recommend storing dbhandle as a variable and access that within get_row using the global scope.
So your code should be like this
<?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;
答
<?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;