doudu22272099831 2017-04-05 17:28
浏览 54
已采纳

Mysqli PHP连接致命错误

I am trying to create a connection from a web form to MySQL database using PHP. My code is as follows:

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();

This part seems to work.. It then connects to 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);

?>

I am getting the following errors:

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /var/sites/i/site/public_html/ContactForm/thankyou.php on line 15

Fatal error: Call to a member function query() on null in /var/sites/i/site/public_html/ContactForm/thankyou.php on line 16

  • 写回答

1条回答 默认 最新

  • douyue8364 2017-04-05 17:31
    关注

    There are several issues with your script:

    1: You need to return the connection likes o:

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

    2: When you run

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

    You have already executed the SQL to the DB, you do not need $success = $conn->query($query);

    So your code should be:

    <?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);
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红
  • ¥15 想问问富文本拿到的html怎么转成docx的
  • ¥15 我看了您的文章,遇到了个问题。
  • ¥15 GitHubssh虚拟机连接不上
  • ¥15 装完kali之后下载Google输入法 重启电脑后出现以下状况 且退不出去 桌面消失 反复重启没用