PHP functions for mysql assoc_array


PHP functions for mysql assoc_array

我正在努力提高我的技能,所以在一个新项目上,我试图将大多数动作存储为函数,以尽量减少重复的代码。

以前我所有的代码都在每个PHP文件的头(一个Dreamweaver风格)

在这个新项目中,我有一个需要拉一个关联数组来显示博客的页面。

当前正在失败。以下是我的文件:

DB.php

<?php
$servername = "localhost";
$username = "USERNAME";
$password = "*******";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
?> 

显然也

function getAllBlogs()
{   
    $sql = "SELECT * FROM blog ORDER BY id DESC ";
    $query = mysqli_query($conn, $sql);
    $result = mysqli_fetch_assoc($query);
            return $result;
}

blog.php

<?php include("../Connections/db.php");?>
<?php include("functions.php");?>
    <?php 
            $result = getAllBlogs();
    foreach($result as $blogs) {
     echo "/".$blogs['id']."_".seoUrl($blogs['title']);
    }
    ?>

我需要在函数文件中包含db.php吗?

显然,我没有把所有的代码,因为有些是HTML样式,但这是我得到的错误

Notice: Undefined variable: conn in /home/classbyt/public_html/functions.php on line 17
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/classbyt/public_html/functions.php on line 17
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in /home/classbyt/public_html/functions.php on line 18
Warning: Invalid argument supplied for foreach() in /home/classbyt/public_html/blog.php on line 33

LINE 33 on BLOG.php是

foreach($result as $blogs) {

第17行&18 . on functions.php is

$result1 = mysqli_query($conn, $sql);
        $result = mysqli_fetch_assoc($result1);

你忘了把它赋值给$result变量

 <?php
        $result=getAllBlogs();// assign to $result variable
        foreach($result as $blogs) {
       echo "/".$blogs['id']."_".seoUrl($blogs['title']);
     } ?>

首先在blog.php中包含functions.php文件。使用下面的代码。

<?php
require_once 'functions.php';
$result = getAllBlogs();
foreach($result as $blogs) 
{
    echo "/".$blogs['id']."_".seoUrl($blogs['title']);
} 
?>

方法getAllBlogs()没有用于返回值的变量。

<?php
$result = getAllBlogs();
foreach($result as $blogs) 
{
    echo "/".$blogs['id']."_".seoUrl($blogs['title']);
} 
?>
编辑:

$conn的作用域有问题。你的mysqli_query()方法不知道$conn变量

显然也

function getAllBlogs()
{   
    global $conn; // -> to get access to the variable, which is outside the method
    $sql = "SELECT * FROM blog ORDER BY id DESC ";
    $query = mysqli_query($conn, $sql);
    $result = mysqli_fetch_assoc($query);
            return $result;
}