Php 如何从数据库中回显包含特定变量的行

Php 如何从数据库中回显包含特定变量的行,php,html,mysql,database,phpmyadmin,Php,Html,Mysql,Database,Phpmyadmin,首先,我的数据库表设置如下: id | affsub |报价|姓名|日期|时间|付款 1 | stringhere | offer | 2017-09-12 | 06:47:00 | 1 我想将包含affsubstringhere的所有行回显到html表中。我试过这个: <?php $id = $get_info_id; $mysqli = new \mysqli('localhost', 'user', 'pass', 'db'); $aff = $mysqli->

首先,我的数据库表设置如下:

id | affsub |报价|姓名|日期|时间|付款

1 | stringhere | offer | 2017-09-12 | 06:47:00 | 1

我想将包含affsubstringhere的所有行回显到html表中。我试过这个:

<?php
   $id = $get_info_id;
   $mysqli = new \mysqli('localhost', 'user', 'pass', 'db');
   $aff = $mysqli->query("SELECT affsub FROM users WHERE id = $id")->fetch_object()->affsub;
   $affsub = $aff;
   $userinfo= $mysqli->query("SELECT offer_name, time, payout FROM conversions WHERE affsub = ". $affsub . "");

  if ($userinfo->num_rows > 0) {
     while($row = $userinfo->fetch_assoc()) {
        echo '<tr>
           <td><b><color=black>' .$row['offer_name'].' </b></td>
           <td><color=black>' .$row['time'].'</td>
           <td>$<color=black>' .$row['payout'].'</td>
        </tr>';
     }
  }
  else {
     echo "<b><center>No Conversions Have Happened.</center></b>";
  }
?>


我知道它得到了affsub,因为如果我回显$affsub,我的affsub会被回显出来,但表上没有显示任何内容,我不确定发生了什么。

您应该简单地将两个查询合并起来:

$userinfo = $mysql->query("SELECT c.offer_name, c.time, c.payout
    FROM conversations AS c
    JOIN users AS u ON u.affsub = c.affsub
    WHERE u.id = $id");

我认为问题在于WHERE子句中搜索词缺少倒逗号。它应该是这样的:affsub='$affsub'

试试这个

$userinfo= $mysqli->query("SELECT offer_name, time, payout FROM conversions WHERE affsub = '$affsub' ");

请注意,我使用的sql语句的积分属于@Barmar,因为他昨天首先想到了连接查询

下面是要使用的两种方法。请注意,我没有使用任何OOP或函数。原因是我想让你有一个所有步骤的紧凑视图


如何使用mysqli准备的语句和异常处理 1.使用get_result()+fetch_object()或fetch_array()或fetch_all(): 此方法(推荐)仅在安装/激活驱动程序mysqlnd(MySQL本机驱动程序)时有效。我认为驱动程序在PHP>=5.3中默认激活。实现代码并让它运行。它应该会起作用。如果它有效,那么它就是完美的。如果没有,请尝试激活mysqlnd驱动程序,例如在php.ini中取消注释
extension=php\u mysqli\u mysqlnd.dll
。否则,必须使用第二种方法(2)

在html代码中也做相应的更改

NB:如何使用fetch_all()代替fetch_object():

//...
if ($numberOfRows > 0) {
    /*
     * Use mysqli_result::fetch_array to fetch a row at a time.
     * e.g. use it in a loop construct like 'while'.
     */
    while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
        $fetchedData[] = $row;
    }
}
//...
//...
if ($numberOfRows > 0) {
    /*
     * Use mysqli_result::fetch_all to fetch all rows at once.
     */
    $fetchedData = $result->fetch_all(MYSQLI_ASSOC);
}
//...
在html代码中也做相应的更改

2.使用store_result()+bind_result()+fetch(): 在没有驱动程序mysqlnd(MySQL本机驱动程序)的情况下工作


示例代码:Mysqli准备的语句和异常处理
桌子{
字体系列:“Verdana”,Arial,无衬线;
字体大小:14px;
边界塌陷:塌陷;
}
表,th,td{
边框:1px实心#ccc;
}
th,td{
填充:7px;
}
泰德{
颜色:#fff;
字体大小:正常;
背景颜色:珊瑚;
}
t脚掌{
背景色:小麦;
}
tfoot td{
文本对齐:右对齐;
}
阴极射线管。不
报盘名称
时间
支出
-找到的记录-
没有找到任何记录。
最后,我建议您使用面向对象的方法,比如实现MySQLiConnection类(用于处理db连接)和MySQLiAdapter类(用于处理查询功能)。这两个类只应实例化一次。MySQLiConnection应该作为构造函数参数传递给MySQLiAdapter类。MySQLiAdapter类需要一个MySQLiConnection类来查询数据库和接收结果。您也可以通过实现相应的接口来扩展它们的使用,但我尽量使我的解释保持简单

我还建议您使用PDO而不是MySQLi。我在实现这段代码时发现的原因之一是:MySQLi中有点挑战性的异常处理系统


祝你好运

您正在尝试将查询结果用作另一个查询中的where子句$userinfo=$mysqli->query(“选择offer_名称、时间、转换支付,其中affsub=“.$affsub.”);是,因为我想使用用户的id,从另一个表中查找用户,并将其用于此目的table@Accountantم我已经解决了这个问题,但现在如何修复sql注入漏洞?不需要,但谢谢。我将其作为一个答案发布,只是因为您需要一个示例,而且这是您查看代码的最佳方式。所以不要接受它。无论如何,也请发布
转换表的列。不,这称为转义参数。如果使用正确的数据库编码,它可以保护您免受SQL注入攻击。但我们人类通常会忘记逃避某些事情。这是关于切换到准备好的语句。搜索主题并等待@aendeerei示例tomorrow@awesomexbox3不客气。尽量使用预先准备好的语句和异常处理。祝你好运。@awesomexbox3 P.S:你的表需要一些重构。这两者在id列上应该是外键关系。好吧,但既然我使用的是用户管理框架,我应该去掉define('MYSQL_HOST','…');定义('MYSQL_PORT','…');定义('MYSQL_数据库','…');定义('MYSQL_字符集','utf8');定义('MYSQL_USERNAME','…');定义('MYSQL_密码','…');然后把它放在我的db文件中,这是最简单的安全方法吗?或者有没有更简单的方法,因为我对cnv的内容感到困惑。是?@awesomexbox3是的,不应在发生数据库连接的页面中定义这些常量。例如,定义一个函数(可能在连接类中)以连接到db。然后,这些连接字符串变量应定义为函数的参数。像
公共函数connect($host,$port,$dbName,…)
。价值观
//...
if ($numberOfRows > 0) {
    /*
     * Use mysqli_result::fetch_all to fetch all rows at once.
     */
    $fetchedData = $result->fetch_all(MYSQLI_ASSOC);
}
//...
<?php
/*
 * Define constants for db connection.
 */
define('MYSQL_HOST', '...');
define('MYSQL_PORT', '...');
define('MYSQL_DATABASE', '...');
define('MYSQL_CHARSET', 'utf8');
define('MYSQL_USERNAME', '...');
define('MYSQL_PASSWORD', '...');

/*
 * Activate PHP error reporting.
 * Use ONLY on development code, NEVER on production code!!!
 * ALWAYS resolve WARNINGS and ERRORS.
 * I recommend to always resolve NOTICES too.
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

/*
 * Enable internal report functions. This enables the exception handling, 
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions 
 * (mysqli_sql_exception). They are catched in the try-catch block.
 * 
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings. 
 * 
 * See:
 *      http://php.net/manual/en/class.mysqli-driver.php
 *      http://php.net/manual/en/mysqli-driver.report-mode.php
 *      http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    // To delete (just for test here).
    $get_info_id = 1;

    $userId = $get_info_id;
    $fetchedData = array();

    /*
     * Create the db connection.
     * 
     * Throws mysqli_sql_exception.
     * See: http://php.net/manual/en/mysqli.construct.php
     */
    $connection = new mysqli(
            MYSQL_HOST
            , MYSQL_USERNAME
            , MYSQL_PASSWORD
            , MYSQL_DATABASE
            , MYSQL_PORT
    );
    if ($connection->connect_error) {
        throw new Exception('Connect error: ' . $connection->connect_errno . ' - ' . $connection->connect_error);
    }

    /*
     * The SQL statement to be prepared. Notice the so-called markers, 
     * e.g. the "?" signs. They will be replaced later with the 
     * corresponding values when using mysqli_stmt::bind_param.
     * 
     * See: http://php.net/manual/en/mysqli.prepare.php
     */
    $sql = 'SELECT 
                cnv.offer_name, 
                cnv.time, 
                cnv.payout 
            FROM conversions AS cnv
            LEFT JOIN users AS usr ON usr.affsub = cnv.affsub 
            WHERE usr.id = ?';

    /*
     * Prepare the SQL statement for execution.
     * 
     * Throws mysqli_sql_exception.
     * See: http://php.net/manual/en/mysqli.prepare.php
     */
    $statement = $connection->prepare($sql);
    if (!$statement) {
        throw new Exception('Prepare error: ' . $connection->errno . ' - ' . $connection->error);
    }

    /*
     * Bind variables for the parameter markers (?) in the 
     * SQL statement that was passed to mysqli::prepare. The first 
     * argument of mysqli_stmt::bind_param is a string that contains one 
     * or more characters which specify the types for the corresponding bind variables.
     * 
     * See: http://php.net/manual/en/mysqli-stmt.bind-param.php
     */
    $bound = $statement->bind_param('i', $userId);
    if (!$bound) {
        throw new Exception('Bind error: The variables could not be bound to the prepared statement');
    }

    /*
     * Execute the prepared SQL statement.
     * When executed any parameter markers which exist will 
     * automatically be replaced with the appropriate data.
     * 
     * See: http://php.net/manual/en/mysqli-stmt.execute.php
     */
    $executed = $statement->execute();
    if (!$executed) {
        throw new Exception('Execute error: The prepared statement could not be executed!');
    }

    /*
     * Transfer the result set resulted from executing the prepared statement.
     * E.g. store, e.g. buffer the result set into the (same) prepared statement.
     * 
     * See:
     *      http://php.net/manual/en/mysqli-stmt.store-result.php
     *      https://stackoverflow.com/questions/8321096/call-to-undefined-method-mysqli-stmtget-result
     */
    $resultStored = $statement->store_result();
    if (!$resultStored) {
        throw new Exception('Store result error: The result set  could not be transfered');
    }

    /*
     * Get the number of rows from the prepared statement.
     * 
     * See: http://php.net/manual/en/mysqli-stmt.num-rows.php
     */
    $numberOfRows = $statement->num_rows;

    /*
     * Fetch data and save it into $fetchedData array.
     * 
     * See: http://php.net/manual/en/mysqli-result.fetch-array.php
     */
    if ($numberOfRows > 0) {
        /*
         * Bind the result set columns to corresponding variables.
         * E.g. these variables will hold the column values after fetching.
         * 
         * See: http://php.net/manual/en/mysqli-stmt.bind-result.php
         */
        $varsBound = $statement->bind_result(
                $resOfferName
                , $resTime
                , $resPayout
        );
        if (!$varsBound) {
            throw new Exception('Bind result error: The result set columns could not be bound to variables');
        }

        /*
         * Fetch results from the result set (of the prepared statement) into the bound variables.
         * 
         * See: http://php.net/manual/en/mysqli-stmt.fetch.php
         */
        while ($row = $statement->fetch()) {
            $fetchedObject = new stdClass();

            $fetchedObject->offer_name = $resOfferName;
            $fetchedObject->time = $resTime;
            $fetchedObject->payout = $resPayout;

            $fetchedData[] = $fetchedObject;
        }
    }

    /*
     * Frees the result memory associated with the statement,
     * which was allocated by mysqli_stmt::store_result.
     * 
     * See: http://php.net/manual/en/mysqli-stmt.store-result.php
     */
    $statement->free_result();

    /*
     * Close the prepared statement. It also deallocates the statement handle.
     * If the statement has pending or unread results, it cancels them 
     * so that the next query can be executed.
     * 
     * See: http://php.net/manual/en/mysqli-stmt.close.php
     */
    $statementClosed = $statement->close();
    if (!$statementClosed) {
        throw new Exception('The prepared statement could not be closed!');
    }

    // Close db connection.
    $connectionClosed = $connection->close();
    if (!$connectionClosed) {
        throw new Exception('The db connection could not be closed!');
    }
} catch (mysqli_sql_exception $e) {
    echo 'Error: ' . $e->getCode() . ' - ' . $e->getMessage();
    exit();
} catch (Exception $e) {
    echo $e->getMessage();
    exit();
}

/*
 * Disable internal report functions.
 * 
 * MYSQLI_REPORT_OFF: Turns reporting off.
 * 
 * See:
 *      http://php.net/manual/en/class.mysqli-driver.php
 *      http://php.net/manual/en/mysqli-driver.report-mode.php
 *      http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver->report_mode = MYSQLI_REPORT_OFF;
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Example code: Mysqli prepared statements & exception handling</title>
    </head>
    <style>
        table {
            font-family: "Verdana", Arial, sans-serif;
            font-size: 14px;
            border-collapse: collapse;
        }

        table, th, td {
            border: 1px solid #ccc;
        }

        th, td {
            padding: 7px;
        }

        thead {
            color: #fff;
            font-weight: normal;
            background-color: coral;
        }

        tfoot {
            background-color: wheat;
        }

        tfoot td {
            text-align: right;
        }
    </style>
    <body>

        <?php
        $countOfFetchedData = count($fetchedData);

        if ($countOfFetchedData > 0) {
            ?>
            <table>
                <thead>
                    <tr>
                        <th>Crt. No.</th>
                        <th>OFFER NAME</th>
                        <th>TIME</th>
                        <th>PAYOUT</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    foreach ($fetchedData as $key => $item) {
                        $offerName = $item->offer_name;
                        $time = $item->time;
                        $payout = $item->payout;
                        ?>
                        <tr>
                            <td><?php echo $key + 1; ?></td>
                            <td><?php echo $offerName; ?></td>
                            <td><?php echo $time; ?></td>
                            <td><?php echo $payout; ?></td>
                        </tr>
                        <?php
                    }
                    ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="7">
                            - <?php echo $countOfFetchedData; ?> records found -
                        </td>
                    </tr>
                </tfoot>
            </table>
            <?php
        } else {
            ?>
            <span>
                No records found.
            </span>
            <?php
        }
        ?>

    </body>
</html>