1

我有一个表格,允许人们将士兵添加到转移到 mysql 的列表中。如果我在没有变量的情况下执行它甚至可以,但是一旦我尝试添加一个如下所示的变量。

// Get Variable from LocalStorage (This has been tested and does indeed return fine)
$affiliation = "<script>document.write(localStorage.getItem('join_affiliation'));</script>";

$sql = 'SELECT * FROM Reenactors WHERE Affiliation="'. $affiliation.'"';

它不想工作。此代码用于在评论页面上显示所有与 Affiliation 相关的 Soliders 的表格。我完全迷失了,现在不知道该怎么做。我希望有人可以帮助我。下面是 PHP 代码的完整列表。

$affiliation = "<script>document.write(localStorage.getItem('join_affiliation'));</script>";

// REMOVED USER AND PASSWORD OF COURSE :D
$con = mysql_connect("localhost","USERNAME","PASSWORD");
if (!con){ die("Can not connect: " . mysql_error()); } 


mysql_select_db("grainger_2013", $con);
$sql = 'SELECT * FROM Reenactors WHERE Affiliation="'$affiliation'"';
$myData = mysql_query($sql, $con);

// ECHO TABLE CONTENTS      
while($row = mysql_fetch_array($myData)){
    echo "<tr>";
    echo "<td>" . $row['ID'] . "</td>";
    echo "<td>" . $row['Side'] . "</td>";
    echo "<td>" . $row['Role'] . "</td>";
    echo "<td>" . $row['First_Name'] . "</td>";
    echo "<td>" . $row['Last_Name'] . "</td>";
    echo "</tr>";
}

// TEST VARIABLE (Does work)
echo '<p>' . $affiliation . '</p>';

mysql_close($con);

作品...

$sql = 'SELECT * FROM Reenactors WHERE Affiliation = "TEST"';

不工作...

$sql = 'SELECT * FROM Reenactors WHERE Affiliation = "' $affiliation '"';

$sql = 'SELECT * FROM Reenactors WHERE Affiliation = "' . $affiliation . '"';

$sql = 'SELECT * FROM Reenactors WHERE Affiliation = "' . mysql_real_escape_string($affiliation) . '"';

$sql = sprintf("SELECT * FROM Reenactors WHERE Affiliation= '%s'",mysql_real_escape_string($affiliation));

$sql = "SELECT * FROM Reenactors WHERE Affiliation LIKE \"$affiliation\"";

$sql = "SELECT * FROM Reenactors WHERE Affiliation = \"$affiliation \"";
4

3 回答 3

3

您的逻辑是错误的,您正在混合概念:

  • 服务器端:PHP、MySQL
  • 客户端:HTML、CSS、JS

PHP无法通过这种方式与浏览器交互,流程如下:

  1. 浏览器向服务器发送请求以查看页面
  2. 服务器将一些信息传递给 PHP
  3. PHP 完成它的工作并生成文本作为输出(通常是 HTML)
  4. 文本被浏览器解释为 HTML 来呈现页面,可能还有 CSS 和 JS
  5. 浏览器执行 JS 代码并做它想做的任何事情
  6. 重复

您需要牢记这一点来构建您的代码:浏览器是否需要X在 PHP 可以做之前做Y?那么 PHP 应该检查if (browser did X) { ... do Y ... } else { tell browser "Do X" }.

如果浏览器正在执行X并需要来自服务器的信息,那么加载带有查询的新 URL 可能会检索该信息,显然您需要一个新的 PHP 脚本来回答该查询。

第二部分

把你的逻辑分成几个步骤:

  1. 从数据库中准备好你需要的信息,使用 PHP 构建 HTML 并在需要时添加一些 JS 值,将页面发送到浏览器
  2. 允许浏览器确定接下来需要什么信息,如果用户不应该离开当前页面但浏览器需要进一步的数据库信息,则发送异步AJAX请求
  3. 准备一个新的 PHP 脚本来响应 AJAX 请求,验证需要什么,如果可能的话用JSONjson_encode()返回信息( )以简化浏览器的过程
  4. 仍然在浏览器中,JS 将接收 AJAX 响应,对其进行解析,并采取一些行动
  5. 根据您的应用程序/脚本的逻辑,您可能需要根据用户操作准备更多信息以再次发送到服务器

实施你的想法

有不同的策略可以实现您想要做的事情,有些可能很容易,有些可能很难,您选择的策略将取决于它如何与您的其余代码或想法相匹配。

根据您的描述:

  • 浏览器存储了一个值
  • PHP需要说值
  • DB 将检索匹配列表
  • 浏览器将显示这些匹配项

所以:

  1. 用户需要先访问该页面,此时页面在任何Reenactors地方都没有列表显示,但它可以显示一条消息,说明它正在处理列表
  2. 页面加载后,一个小脚本会检索该join_affiliation值并将 AJAX 请求发送到某个脚本,例如reenactors.php?affiliation=<join_affiliation>
  3. 用户同时看到一个纺车
  4. AJAX 请求返回:
    • 错误:给用户的消息“没有找到从属关系的重演者”
    • 成功:创建列表,或者添加列表(取决于 PHP 脚本的响应)

重要提示mysql_*函数系列已被弃用,不鼓励使用,因为它的低级控制允许从不熟练的编码人员的代码中轻松执行恶意查询。推荐使用PDO

反应器列表:

/**
 * By now, assume no errors when connecting to the DB
 */
$db = new PDO('mysql:host=localhost;dbname=<SOMEDB>','<USERNAME>','PASSWORD');
$affiliation = '<any>';

if (isset($_GET['affiliation'])) {
    $affiliation = $_GET['affiliation'];

    /**
     * Dynamic values are indicated by the question mark
     * Named variables are also possible:
     * http://www.php.net/manual/en/pdostatement.bindparam.php
     *
     * No quotes around the placeholder of the string
     */
    $statement = $db->prepare('SELECT * FROM Reenactors WHERE Affiliation=?');
    $statement->bindValue(1,$affiliation);
}
else {
    $statement = $db->prepare('SELECT * FROM Reenactors');
}

/**
 * The query statement is ready, but hasn't executed yet
 * Retrieve/fetch all results once executed
 * http://www.php.net/manual/en/pdostatement.fetchall.php
 *
 * Some prefer to read row by row using fetch()
 * Use it if the script starts to use too much memory
 */
$statement->execute();
$reenactors = $statement->fetchAll(PDO::FETCH_ASSOC);


/**
 * Display the affiliation, as part of the table
 * Assume the table will have 5 columns
 */
?>
    <tr>
        <th colspan="5">Affiliation: <?php echo htmlspecialchars($affiliation) ?></th>
    </tr>
<?php

/**
 * Display the list
 * Assume the text can contain HTML and escape it
 * http://www.php.net/manual/en/function.htmlspecialchars.php
 */
foreach ($reenactors as $reenactor) { ?>
    <tr>
        <td><?php echo htmlspecialchars($reenactor['ID']) ?></td>
        <td><?php echo htmlspecialchars($reenactor['Side']) ?></td>
        <td><?php echo htmlspecialchars($reenactor['Role']) ?></td>
        <td><?php echo htmlspecialchars($reenactor['First_Name']) ?></td>
        <td><?php echo htmlspecialchars($reenactor['Last_Name']) ?></td>
    </tr>
<?php }

/**
 * What if, for some reason, the list is empty?
 */
if (!count($reenactors)) { ?>
    <tr>
        <td>
            This list is empty
        </td>
    </tr>
<?php }

动态显示 reenactors 列表(假设使用jQuery

<html>
<head>
    <title>Reenactors of Historic Place Historic Event</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script>
    /**
     * Wait until the document is ready
     */
    $(document).ready(function(){
        /**
         * Be warned, not all the browsers support localStorage
         * This line might cause an error at those browsers
         */
        var affiliation = localStorage.getItem('join_affiliation') || '';

        /**
         * jQuery.ajax http://api.jquery.com/jQuery.ajax/
         * affiliation needs to be encoded to be added to the URL
         *
         * The request will start at this moment, and finish at an
         * undefined moment in the future
         *
         * success or error function will execute at that moment
         */
        $.ajax({
            url: 'reenactors.php?affiliation=' + encodeURIComponent(affiliation),
            error: function(){
                /**
                 * In case of error, find the table and show a message
                 */
                $('#reenactors-list td').text('There was a problem generating the list, please try later');
            },
            success: function(data_from_server){
                /**
                 * data_from_server will contain the list generated by the script
                 */
                $('#reenactors-list tbody').html(data_from_server);
            }
        });
    });
    </script>
</head>
<body>
    <h1>Reenactors</h1>
    <table id="reenactors-list">
        <tbody>
            <tr>
                <td>
                    The list of reenactors is loading, please wait... [spinning image here]
                </td>
            </tr>
        </tbody>
    </table>
</body>
</html>
于 2013-06-25T04:21:17.557 回答
-1

改成这个

$sql = "SELECT * FROM Reenactors WHERE Affiliation='". $affiliation."'";
于 2013-06-25T04:13:11.997 回答
-1

尝试这个,

$sql = "SELECT * FROM Reenactors WHERE Affiliation LIKE \"$affiliation\"";
于 2013-06-25T04:27:55.950 回答