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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭