How do I use mysqli in an included file when the m

2020-05-09 17:37发布

问题:

I'm about to use mysqli instead of mysql for the first time in my procedural PHP application.

index.php

include(db_conn.php);

<html>
<body>
    <?php include(content.php);?>
</body>
</html

db_conn.php

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

content.php

mysqli_query($con,"SELECT * FROM Persons");
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
# more code...

mysqli_query necessarily requires the connection variable and my connection is stored in variable $con in the included db_conn.php file which is unavailable in another included content.php file.

回答1:

Within your content.php use require(db_conn.php); And if you have a function defined in there, you're going to have to put require(db_conn.php); INSIDE that function.

The database connection doesn't seem to have exactly the same scoping as a standard variable.

I know when coding it, you feel like "I should only have to include this once!" but shrug get everything else working first, and if someone wants to pay you to go back and try to "fix" this... work on it then. ;)



标签: php mysqli