douzhicai7148 2017-11-02 11:25
浏览 102

无法包含connection.php文件以重用与数据库的连接

I'm having some problem to include a connection file to my php page.

I have this connessione.php which receive from login.php the user and password to connect to my db:

<?php   
    $host="localhost";
    $user=$_POST["username"];
    $password= $_POST["password"];
    $database = "Park";
    $lingua=$_POST["lingua"];
    $myconn= new mysqli($host,$user,$password,$database); 

    if($myconn->connect_error){
        Header('Location: login.html');
    }else{
        Header('Location: form.html');
    }
?> 

This is my form.php that should use the connection.

<?php
    require ('connessione.php');
    $query="SELECT CodicePin from Pin";
    $res=$myconn->query($query);
    $row=$res->fetch_array(MYSQLI_NUM);
    print_r($row);
?> 

The problem is that it is unable to use $myconn established in connessione.php and when I try to login with right user/psw i'll be redirect to login.php.

However if i try to modify connessione.php like this and it execute the query without problem.

<?php   
        $host="localhost";
        $user=$_POST["username"];
        $password= $_POST["password"];
        $database = "Park";
        $lingua=$_POST["lingua"];
        $myconn= new mysqli($host,$user,$password,$database); 

        if($myconn->connect_error){
            Header('Location: login.html');
        }else{
        $query="SELECT CodicePin from Pin";
        $res=$myconn->query($query);
        $row=$res->fetch_array(MYSQLI_NUM);
        print_r($row);
        }
    ?> 

How i can use the same connection established by connessione.php in other php page? Thanks, and sorry about my english :)

  • 写回答

2条回答 默认 最新

  • drdzpknk76046 2017-11-02 11:36
    关注

    In Connection Page, i named DbConfig.php

     // DB connection
        $host="localhost"; // Host name
        $username="root"; // Mysql username
        $password=""; // Mysql password
        $db_name="demoproject"; // Database name
    
        // Connect to server and select databse.
        $con=mysqli_connect("$host", "$username", "$password","$db_name") or die("cannot connect");
    if(mysqli_connect_errno()){
        echo "Failed to Connect Database: ". mysqli_connect_error();
    //You can redirect here
        exit();
    }
    

    in Process Page

    require_once("DbConfig.php");
    
    $sql="SELECT CodicePin from Pin";
    $result=mysqli_query($con,$sql);
    $row=mysqli_fetch_array($result);
    var_dump($row);
    
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮