Mysqli PHP连接致命错误

时间:2017-04-05 17:28:40

标签: php mysql

我正在尝试使用PHP创建从Web表单到MySQL数据库的连接。我的代码如下:

connection.php:

<?php
$link = mysqli_connect("", "", "", "");

if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}

echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

phpinfo();

这部分似乎有效..然后连接到thank you.php:

<?php

function connect()
    {
        $conn = mysqli_connect("", "", "", "");
    }

ini_set('display_errors', 1); error_reporting(~0);

require 'connection.php';
$conn    = Connect();
$query   = mysqli_query($conn,"INSERT into Members (Username) VALUES('1111Username')");
$success = $conn->query($query);

if (!$success) {
die("Couldn't enter data: ".$conn->error);

}

echo "Thank You For Contacting Us <br>";

mysqli_close($conn);

?>

我收到以下错误:

  

警告:mysqli_query()要求参数1为mysqli,在第15行的/var/sites/i/site/public_html/ContactForm/thankyou.php中给出为null

     

致命错误:在第16行的/var/sites/i/site/public_html/ContactForm/thankyou.php中调用null上的成员函数query()

1 个答案:

答案 0 :(得分:0)

您的脚本存在以下几个问题:

1:您需要返回类似o:

的连接
function connect()
{
    return mysqli_connect("", "", "", "");
}

2:当你跑步时

$query   = mysqli_query($conn,"INSERT into Members (Username) VALUES('1821Username')");

您已经将SQL执行到数据库,您不需要$success = $conn->query($query);

所以你的代码应该是:

<?php

function connect()
    {
        return mysqli_connect("", "", "", "");
    }

ini_set('display_errors', 1); error_reporting(~0);

require 'connection.php';
$conn    = connect();
$query   = mysqli_query($conn,"INSERT into Members (Username) VALUES('1821Username')");

if (!$query) {
die("Couldn't enter data: ".$conn->error);

}

echo "Thank You For Contacting Us <br>";

mysqli_close($conn);

?>