简体   繁体   English

将PHP函数与数据库集成

[英]Integrating PHP functions with a database

I just submitted my work and my course leader has asked me to use PHP functions to query my database. 我刚刚提交了我的工作,而课程负责人要求我使用PHP函数来查询数据库。 How can I do this? 我怎样才能做到这一点? Is it possible to add just "function getRooms" before my queries, and return the desired result. 是否可以在查询之前仅添加“ function getRooms”,并返回所需结果。 I need thorough briefing on functions with MySQL . 我需要有关MySQL函数的详尽介绍。

For example: How will I add a function to this code: 例如:如何将函数添加到此代码中:

<?php
    // By Kelvin
    include ("player.php");
    $result = mysql_query("SELECT * FROM phplogin WHERE username = '$username'");
    $row = mysql_fetch_assoc($result);
    $medipack = $row['medipack'];
    if ($_POST['object'] == "Use Medipack") {
        if ($medipack != 0) {
            mysql_query("UPDATE phplogin SET score = score + 50, health = health + 50, medipack = medipack - 1
            WHERE username = '$username'");
            echo ("<P>Medipack Used!</P>");
            $RoomNumber =5;
        }
        else {
            echo ("<P>You're all out of medipacks!</P>");
        }
    }
?>

If he's looking for a level of abstraction between the rest of your code and the code accessing the database, wrapping the database logic in functions should be on the right path: 如果他正在寻找其余代码与访问数据库的代码之间的抽象层次,那么将数据库逻辑包装在函数中应该在正确的路径上:

function getRooms($link){
    $sql = "SELECT * FROM rooms";
    $data = array();
    if($set = mysql_query($sql)){
        while($row = mysql_fetch_assoc($set)){
            $data[] = $row;
        }
    }
    return empty($data)
        ? null
        : $data;
}

$db_connection = mysql_connect('host', 'user', 'pass');
mysql_select_db('name', $db_connection);
$rooms = getRooms($db_connection);

Wrapping these functions into a class, and accessing them by methods is another step, as the instantiated object can manage its own connection, etc., but that may be a step further than necessary. 将这些函数包装到一个类中,并通过方法访问它们是另一个步骤,因为实例化的对象可以管理其自己的连接等,但这可能比必要的步骤要远。 Other functions (based on what I can guess) might be: 其他功能(根据我的猜测)可能是:

function getRoomById($link, $id){ }
function getRoomsByName($link, Array $names){ }

我想您的课程负责人是指PHP的本机MySQL函数-http://php.net/manual/zh/book.mysql.php

You can wrap your queries inside PHP functions. 您可以将查询包装在PHP函数中。 For example, like this: 例如,像这样:

function &getRooms(){
    $query="SELECT id,name FROM rooms";
    $result=mysql_query($query);

    $ar_out=array();
    while ($row = mysql_fetch_assoc($result)) {
        $ar_out[]=$row;
    }
    return $ar_out;
}

This said, you really should find a tutorial or a book on how to use MySQL and PHP together. 也就是说,您确实应该找到有关如何一起使用MySQLPHP的教程或书籍。 There are many things to know about code organization and performance. 关于代码的组织和性能,有很多事情要知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM