mysql中的PHP变量调用$ sql(SELECT * FROM示例WHERE示例=“$ example”)

时间:2013-06-25 04:04:08

标签: php mysql local-storage

我有一个表单,允许人们将士兵添加到列表中,转移到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 \"";

3 个答案:

答案 0 :(得分:3)

你的逻辑错了,你在混合概念:

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

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

  1. 浏览器向服务器发送请求以查看页面
  2. 服务器将一些信息传递给PHP
  3. PHP完成其工作并生成文本作为输出(通常为HTML)
  4. 浏览器将文本解释为HTML以呈现页面,可能还有CSS和JS
  5. 浏览器执行JS代码并执行它意味着做的任何事情
  6. 重复
  7. 您需要在构建代码时考虑到这一点:在PHP可以执行X之前,浏览器是否需要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请求,验证需要什么,如果可能的话{(3}})返回信息(JSON)以简化浏览器的过程
    4. 仍然在浏览器中,JS将收到AJAX响应,解析它并采取一些行动
    5. 根据您的应用程序/脚本的逻辑,您可能需要根据用户操作再次准备要在服务器上发送的更多信息
    6. 实施您的想法

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

      根据您的描述:

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

      所以:

      1. 用户首先需要访问该页面,此时该页面没有Reenactors列表显示在任何地方,但它可以显示一条消息,指出它正在处理列表
      2. 一旦页面加载,一个小脚本将检索join_affiliation值并将AJAX请求发送到某些脚本,如reenactors.php?affiliation=<join_affiliation>
      3. 用户同时看到一个纺车
      4. AJAX请求返回:
        • 错误:向用户发送消息“找不到联盟的reenactors”
        • 成功:创建列表,或添加列表(取决于PHP脚本的响应)
      5. 重要mysql_*系列函数已被弃用,不鼓励使用它,因为它的低级控制允许从不熟练编码器的代码轻松执行恶意查询。建议使用json_encode()

        Reenactors列表:

        /**
         * 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列表(假设使用PDO

        <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>
        

答案 1 :(得分:-1)

更改为

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

答案 2 :(得分:-1)

试试这个,

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