php - 正确的 mysqli_query 和 mysqli_error 配置

标签 php mysql mysqli

当启动我的代码时,我得到一个失败的查询和以下错误:

mysqli_query() expects parameter 1 to be mysqli, null given in

mysqli_error() expects parameter 1 to be mysqli, string given in

<?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 函数?

最佳答案

上面的代码有两个错误:

  • 您错过了将 $link global 声明为 $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;
}

关于php - 正确的 mysqli_query 和 mysqli_error 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14002994/

相关文章:

PHP Mysqli 接连触发查询

php - 存储过程中的 SQL 注入(inject)?

php - 禁用 SonataUserBundle sonata.user.admin.group 服务

php - 插入html内容到mysql表

php - 您如何从同一个表中引用多个查找?

java - 在不影响速度的情况下在 MySQL 中检索大型结果集

php - 如何从 php 运行 Python 脚本

php - 使用 PHP 动态表列

c# - 如何修复在asp.net中执行命令时遇到的 fatal error

php - 调用 PHP 对象文件导致页面不再加载