2

我有一个带有 2 个参数的函数。这里是

function listBoats($con,$table){
    //get record set for all boats sort them by their "sort" number
    $queryBoat = "SELECT * FROM " .$table. " WHERE `id` <> 'mainPage' ORDER BY `sort` LIMIT 0, 1000";
    $result = mysqli_query($con,$queryBoat);
    return $result;
}

我是这样称呼它的

$result = listBoats($con,"CSINSTOCK"); //run query to list all the boats in the CSINSTOCK table

我无法让它工作。但是,如果我$table = "CSINSTOCK"在函数中添加变量,它确实可以工作。为什么函数不会通过"CSINSTOCK"变量?

4

1 回答 1

-1

我建议你使用 PDO。这是一个例子

例子。 这是您的 dbc 类 (dbc.php)

<?php

class dbc {

    public $dbserver = 'server';
    public $dbusername = 'user';
    public $dbpassword = 'pass';
    public $dbname = 'db';

    function openDb() {    
        try {
            $db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
        } catch (PDOException $e) {
            die("error, please try again");
        }        
        return $db;
    }

    function getAllData($qty) {
        //prepared query to prevent SQL injections
        $query = "select * from TABLE where qty = ?";
        $stmt = $this->openDb()->prepare($query);
        $stmt->bindValue(1, $qty, PDO::PARAM_INT);
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $rows;
    }    
?>

您的 PHP 页面:

<?php 
require "dbc.php";

$getList = $db->getAllData(25);

foreach ($getList as $key=> $row) {
         echo $row['columnName'] .' key: '. $key;
    }

如果您有权访问您的数据库,您应该能够执行所需的操作。

于 2013-06-10T17:45:39.563 回答