【问题标题】:PHP Variable in mysql call $sql( SELECT * FROM Example WHERE Example = "$example" )mysql 调用 $sql( SELECT * FROM Example WHERE Example = "$example" ) 中的 PHP 变量
【发布时间】:2013-06-21 18:09:25
【问题描述】:

我有一个表格,允许人们将士兵添加到列表中,该列表可以很好地转移到 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 \"";

【问题讨论】:

  • "It doesn't want to work." 不是一个有效的问题。您的预期结果是什么,您目前获得的结果是什么?
  • $affiliation 是一个 js 字符串,嗯,它真的是你的数据库中的内容吗?
  • 如果您在$sql 中使用带有字符串连接的相同代码,它可能会正常工作。你还应该正确地转义 MySQL 中的字符串。
  • 我刚刚更新了它。基本上我需要它从数据库中获取当前的隶属关系并显示所有相关士兵的表格。该变量正在从 Localstorage 中提取 Affiliation,我需要在 ( WHERE Affiliation = "HERE" ) 调用中使用它。但它返回空而没有错误,一旦我插入一个静态变量它就可以工作。
  • 您无法通过 PHP 访问 localstorage。

标签: php mysql local-storage


【解决方案1】:

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

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

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

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

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

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

第二部分

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

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

实现你的想法

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

根据您的描述:

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

所以:

  1. 用户需要先访问页面,此时页面在任何地方都没有Reenactors列表显示,但可以显示一条消息,说明它正在处理列表
  2. 页面加载后,一个小脚本会检索join_affiliation 值并将AJAX 请求发送到某个脚本,例如reenactors.php?affiliation=&lt;join_affiliation&gt;
  3. 用户同时看到一个纺车
  4. AJAX 请求返回:
    • 错误:向用户发送消息“未找到关联的 reenactors”
    • 成功:创建列表,或者添加列表(取决于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 }

动态显示重演者列表(假设使用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>

【讨论】:

  • 这是我一直以来的印象,但我能够使用 PHP 访问 localstorage 文件就好了,所以我打算使用它。但我不知道该怎么做。我需要检查输入的隶属关系是什么,以便显示士兵表。它是动态的,并且会(似乎会)是很多我没有经验的工作。
【解决方案2】:

改成这个

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

【讨论】:

  • 在sql查询中放置变量时应该使用mysql_real_escape_string
  • 是的,正确的。如果要使用mysql_real_escape_string(), $sql = sprintf("SELECT * FROM Reenactors WHERE Affiliation= '%s'",mysql_real_escape_string($affiliation));
  • 注意顶部的代码部分。我以前试过这个,但仍然没有:\
  • @Z33GHOST 你尝试使用mysql_real_escape_string了吗?
  • 还是不行... $sql = 'SELECT * FROM Reenactors WHERE Affiliation = "' . mysql_real_escape_string($affiliation) . '"';
【解决方案3】:

试试这个,

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

【讨论】:

  • 刚刚做了一些改动,可以试试吗?
  • 也没用 刘海头放在桌子上 我认为这是一个 1D10T 错误 XD
  • 好吧,只是为了调试这个东西,echo"$affiliation"; $sql = $sql = "SELECT * FROM Reenactors WHERE Affiliation LIKE \"$affiliation\"";回声“$ sql”;这应该让您知道我们在哪里搞砸了。
  • 这就是我得到的一个错误:警告:mysql_fetch_array():提供的参数不是第 163 行 /FILELOCATION/ 中的有效 MySQL 结果资源。163 是 while($row = mysql_fetch_array($ myData)){ 回显表代码 }
  • Noo,我的意思是注释掉所有使用 DB 中的结果的 PHP 东西。只保留这 3 行。检查第三件事的输出,看看它是否在 phpmyadmin 中以确切的形式工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
  • 2014-08-20
  • 1970-01-01
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多