I have a problem and I've looked around online but I can't find the answer becuse the problems that are brought up aren't exactly the same as mine. I have a project in school where we are supposed to create a blog using php, mysqli, html, css and JavaScript. For the database part I found a site where they showed an example of how you can write the code. My problem: the code isn't working. I have one php-document where I have included different other documents, one of which contain a function with the following code:
global $connect;
$connect = mysqli_connect("localhost", "username", NULL, "database");
After I included the document with this code I included another with the following code:
<?php
/* Returns all published posts
*/
function getPublishedPosts() {
// use global $connect in function
global $connect;
$sql = "SELECT * FROM posts WHERE published=true";
$result = mysqli_query($connect, $sql);
// fetch all posts as an associative array called $posts
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
return $posts;
}
// more functions to come here ...
?>
This is the code that I'm having trouble with, I'm getting the following errors:
Notice: Undefined variable: connect in D:\XAMPP\htdocs\pfunctions.php on line 10
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in D:\XAMPP\htdocs\pfunctions.php on line 10
Warning: mysqli_fetch_all() expects parameter 1 to be mysqli_result, null given in D:\XAMPP\htdocs\pfunctions.php on line 13
I have tried making $connect global in both docs, making it global only in the last one (the way it was in the tutorial) I have tried adding the entire code of $connect to the second doc and it's just not working.
Second I read that mysqli_fetch_all() only works if you have mysqli driver and I don't think my school does and I have no idea how to write it instead, and I hoped you guys could help me with that as well. I'm very new to this so please don't be too hard on me. Thank you!