2012-12-22 47 views
1

当启动我的代码我得到一个失败的查询和以下错误:正确mysqli_query和mysqli_error配置

mysqli_query()预计参数1是mysqli的,空在

mysqli_error给予()预计参数1为库MySQLi,字符串中

<?php 
include('mysql_config.php'); 

function mysqlConnect() 
{ 
    global $mysql_hostname, $mysql_username, $mysql_password, $mysql_database; 
    $link = mysqli_connect($mysql_hostname, $mysql_username, $mysql_password) 
    or die('Could not connect: ' . mysqli_error()); 
    mysqli_select_db($link,$mysql_database) or die('Could not select database'); 
    return $link; 
} 

function mysqliClose($link) 
{ 
    mysqli_close($link); 
} 

function sendQuery($query) 
{ 
    $result = mysqli_query($link, $query) or die('Query failed: ' . mysqli_error("could not query")); 
    return $result; 
} 

?>

给出

如何正确格式化mysqli_query和mysqli_error函数?

+1

'$ link'从哪里来?检查你的'sendQuery'函数..错误很明显..'$ link'没有被定义.. –

+2

你有一个范围问题:http://php.net/manual/en/language.variables.scope.php –

+0

你最好考虑更改'或死(...)'处理错误的方法。首先请访问http://www.phpfreaks.com/blog/or-die-must-die。 – peterm

回答

2

有上面代码中的两个错误:

  • 你错过了申报$linkglobal$mysql_hostname
  • 您传递了错误的参数类型mysqli_error(),预计mysqli,你通过了string

我改变了你的例子:

<?php 

include('mysql_config.php'); 

// declaring an additional global var. 
$link = NULL; 

function mysqlConnect() 
{ 
    global $link; // using the global $link 
    global $mysql_hostname, $mysql_username, $mysql_password, $mysql_database; 
    $link = mysqli_connect($mysql_hostname, $mysql_username, $mysql_password) 
    or die('Could not connect: ' . mysqli_connect_error()); 
    mysqli_select_db($link,$mysql_database) or die('Could not select database'); 
    return $link; 
} 

function mysqliClose($link) 
{ 
    mysqli_close($link); 
} 

function sendQuery($query) 
{ 
    global $link; // using the global $link 
    $result = mysqli_query($link, $query) or die('Query failed: ' 
     . mysqli_error($link)); // note $link is the param 
    return $result; 
} 
+0

在一个声明'die('无法连接:'。mysqli_error())''你最好使用'mysqli_connect_error()'而不是'mysqli_error()'。见[mysqli_connect](http://php.net/manual/en/mysqli.construct.php) – peterm

+0

谢谢!更新了示例 – hek2mgl