John Smith
John Smith

Reputation: 387

Proper mysqli_query and mysqli_error configuration

When launching my code I get a failed query and the following errors:

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;
}

?>

How do I properly format the mysqli_query and mysqli_error functions?

Upvotes: 1

Views: 6676

Answers (1)

hek2mgl
hek2mgl

Reputation: 158070

There are two errors in the code above:

  • You missed to declare $link global as $mysql_hostname etc.
  • You passed the wrong argument type to mysqli_error() it expects mysqli and you passed a string

I have changed your example:

<?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;
}

Upvotes: 2

Related Questions