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

问题描述 投票:1回答:3

我有一个表单,允许人们将士兵添加到列表,转移到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 \"";
php mysql local-storage
3个回答
3
投票

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

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

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

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

您需要在构建代码时考虑到这一点:在PHP可以执行X之前,浏览器是否需要执行Y?那么PHP应该检查if (browser did X) { ... do Y ... } else { tell browser "Do X" }

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

第二部分

将您的逻辑划分为以下步骤:

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

Implementing your idea

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

从您的描述:

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

所以:

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

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

Reenactors list:

/**
 * 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 }

Show list of reenactors dynamically (assumes use of 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>

-1
投票

改为这个

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

-1
投票

试试这个,

$sql = "SELECT * FROM Reenactors WHERE Affiliation LIKE \"$affiliation\"";
© www.soinside.com 2019 - 2024. All rights reserved.