如何将数组解析为变量(PHP)?

时间:2017-04-24 00:42:14

标签: php mysql

对于我的生活,我无法让它发挥作用。我已经查看过很多关于stackoverflow的文章,所以如果你能提供帮助那就太棒了!我正在为客户提交表单。他们希望能够从下拉列表中选择多个值,然后我将从数据库中提取以获取其查询结果。

<form id="test" action="results.php" method="POST">
<select id="role" name="role[]" multiple>
<option value="Student">Student</option>
<option value="Faculty">Faculty</option>
<option value="Alumni">Alumni</option>
</select>

<?php
$query="SELECT City FROM Cities";
$result = mysqli_query($link, $query);
echo '<select name="city" id="city" multiple>';
while($r = mysqli_fetch_assoc($result)){
echo '<option value="'.$r['City'].'">'.$r['City'].'</option>'; }
?>
</select>
<input type="submit"/>
</form>

// results.php

$results=array();

$results[] = $_POST['role'];

$results[]= $_POST['city'];

echo "<pre>";
print_r($results);
echo "</pre>";

**如何从数组中获取所有值并将其解析为单独的变量,以便在SQL语句中使用变量?这是我的输出:**

Array
(
[0] => Array
    (
        [0] => Faculty
        [1] => Alumni
    )

[2] => Adams
)

非常感谢您的帮助! :)如果有更好的方法,请告诉我。

2 个答案:

答案 0 :(得分:2)

[编辑]:此代码对SQL Injection开放,请不要使用它。

  

我在问题中已经有一个提交选项,我创建了一个   城市的虚拟提交选项,在不同的文件中运行此代码,   选择不同的不同选项,然后单击提交按钮,   检查我们的查询是如何构建的   请先阅读说明,并确保阅读代码中的注释,因为它们比代码更重要

注意1-&gt; 简而言之,您希望根据用户选择的选项运行查询, 确保你阅读评论以理解逻辑,评论比它自己的代码更重要,

注意事项2-> 以及我没有意识到的更多事情,您可能会将您的值存储在不同的表中,如果是这样的话,代码会稍微改变一下,但是基本shell将保持不变

注意3-&gt; 为了实现您想要实现的目标,您基本上必须根据设置的选项创建查询,而不是使用IN关键字,你很高兴,

注意4-&gt; 我添加了echo语句,所以你可以逐步看到我们的查询是如何开发的,我添加了评论,如果你想看看只是删除评论,我没有在最后一个回显中添加注释,以便您可以看到准备使用的查询字符串

再次注意 - &gt; 我已经拥有一个提交选项,一个是我自己创建的,所以你可以看到发生了什么,然后你会为你解决问题。

  

正如您在评论中所说,您的表单中可能包含12个字段,如果是这样的话,请使用此代码,因为如果您需要更改,请说明   未来的某些事情,你必须在两个地方改变,   你会犯错误,比如错过某些东西,或者使用错误的变量   或者其他一些东西,使用这段代码,你必须把它改成一个地方,   并且它将适用于12或24个地方,没有的地方数量   物,

还有一件事,如果你将这个PHP代码包装在函数内部会更好,原因就是假设你在其他页面上有表单,而你只需要相同的功能要做,只需要调用函数,将来如果你改变了一些东西,只需更改函数代码

即可

我给你的代码示例为什么最好将它包装在一个函数中,让我们说你的表名与表单中给定的选定名称不同,或者你决定挖洞值在不同的表中,你必须更改代码,如果你写了12次或每个表单,而不是你必须改变它,而不是你遇到大麻烦,但如果你使用这个代码作为不同形式的函数,你只需要在功能上或在这里做一些改变,并且会在任何地方得到应用,很快你搞砸了一些东西的机会就不是他们的了,所以希望这完全有助于你

SideNote - 我想说的另一件事,这个解决方案看起来很大的原因,是因为笔记,表单和注释,如果算上php代码行,没有最后一个回声声明,它实际上只有10行PHP代码,所以不要害怕,因为它看起来很大

    <form id="test" action="" method="POST">
<select id="role" name="role[]" multiple>
<option value="Student">Student</option>
<option value="Faculty">Faculty</option>
<option value="Alumni">Alumni</option>
</select>

<select id="city" name="city[]" multiple>
<option value="London">London</option>
<option value="Paris">Paris</option>
<option value="New York">New York</option>
</select>
    <input type="submit">
</form>
<?php
//creating variable and saying all the post request is equal to this variable
$selected_options=$_POST;
foreach($selected_options as $key=>$option){
    $countValue = count($option);
    for($i=0; $i<$countValue; $i++){
        /*
         * start adding the value seperated by coma, remember again it going to
         *  be on extra coma so we have to remove it.
         */

        $queryString_start_with_coma .= ",$option[$i]";
    }
    /*
     * come out of loop, and now remove that extra coma
     */
    $queryString_remove_extra_come= preg_replace("/,/", "", $queryString_start_with_coma, 1);
    /*
     * start building your query, use variable $key, just check the line below,
     * you will understand where and why i am using variable $key.
     */
    $query_string_with_and .= " AND $key IN($queryString_remove_extra_come)"; 

    /*
     * now unset the variable, this line is very important, so please also check
     * your out come without this line, 
     * what i am simply  doing is emptying the variable, if you dont 
     * do it, it will add the value in the existing value, which i dont want, what 
     * i want when the loop run for the second selected options, i want my variable
     * to be empty, so i can create new string
     * you will understand more if you remove this line and compare your two outcome
     * Note: you dont have to unset if you dont want to, but you have empty the 
     * variable, you can also do by creating a empty string, do what ever you want
     * to do, just make sure the variable is empty for the second loop
     */
    unset($queryString_start);
}

$query_string_second_part_ready = preg_replace("/AND/", "", $query_string_with_and, 1);
//echo "$query_string_second_part_ready<br>";
$query_string= "SELECT * FROM table_name WHERE ".$query_string_second_part_ready;
//see how your query look like
echo $query_string;

答案 1 :(得分:0)

听起来您希望能够根据用户提交的数据构建查询。如果你有多个表,这可能会有点复杂,但基本的想法是使用带有字段的输入名称,从中汇编查询,准备语句并绑定参数。

将输入命名为与

匹配的数据库字段相同
// Identify which database fields can be searched
// These names must match the names of the inputs
// Each name has a type which will be used later
$databaseFields = [ 'city' => 's', 'name' => 's', 'grade' => 'i' ];
$databaseFieldNames = array_keys($databaseFields);

// Set up the beginning of the query
$query = 'SELECT * FROM some_table WHERE ';

// Initialize an array to use to store fields to be searched
$where = [];

// Loop through all the post data
foreach ($_POST as $name => $value) {

    // If the name is in the database fields list, add it to the query
    if (in_array($name,$databaseFieldNames)) {
        $where[] = $name;
    }
}

// Add all the requested columns to the where
if (!empty($where)) {
    $query .= ' '.$where[0].'=?';
    array_pop($where);
    foreach ($where as $name) {
        if (is_array($_POST[$name])) {
            // Use any to check for multiple possible values
            $query .= ' AND '.$name.' = ANY (?)';
        } else {
            $query .= ' AND '.$name.'=?';
        }
    }
} else {
    // Avoid an empty WHERE which will cause an error
    $query .= ' TRUE';
}

$stmt = mysqli_prepare($query);

/* Bind parameters */
foreach ($where as $name) {
    // $_POST should be validated here
    if (is_array($_POST[$name])) {
        // Arrays are imploded to work in an ANY
        $value = "'".implode("','",addslashes($_POST[$name]))."'";
    } else {
        // Other values are used as sent
        $value = $_POST[$name];
    }
    $type = $databaseFields[$name];
    $stmt->bind_param($type,$value);
}

$stmt->execute();
相关问题