【问题标题】:Using post array in php code在 php 代码中使用 post 数组
【发布时间】:2013-10-06 01:27:32
【问题描述】:

我正在尝试编写 php 代码,但在使用 post 数组时遇到了一些问题。我试图访问该数组以便可以放入 MySQL,但无论我尝试什么,该数组总是以空结束。这是我的代码的副本。非常感谢任何帮助。

<?php
//$comment=$_POST['Comment'];
require login.php; //Defines $host, $username, $password and $database with login credentials

$con=mysqli_connect($host, $username, $password, $database);
if(mysqli_connect_errno())
    echo "Failed to connect to MySQL: ".mysqli_connect_error();

if(isset($_POST[Comment]))
{
    $comment=getPost('Comment');
    echo "The comment is: $_POST[0]";
}
$date= getDate();
if(!mysqli_query($con, "INSERT INTO Comments(Date, Type, User, Comment) 
 VALUES ('$date[month]-$date[mday]-$date[year]', 0,'Jimmy Barrientos', '$comment')"))
{
    echo"INSERT failed: <br/>".mysql_error()."<br/><br/>";
}

echo <<<_END
<form action="addComment.php" method="get"><pre>
Comment<br/>
<textarea rows="5" cols="50" name="Comment">
Type in comment here
</textarea>
<input type="submit" value="Add Comment"/>
</pre></form>
_END;

function getPost($var)
{
    return mysql_real_escape_string($_POST[$var]);
}
?>

【问题讨论】:

    标签: php html mysql arrays http-post


    【解决方案1】:

    你省略了引号:

    if(isset($_POST[Comment])) //<--- here
    {
        $comment=getPost('Comment');
        echo "The comment is: $_POST[0]";
    

    【讨论】:

    • 不,还有一个... :)
    【解决方案2】:

    数字 1:在字符串数组索引周围加上引号

    if(isset($_POST["Comment"]))
                    ^       ^
    

    数字 2: 由于您使用的是 mysqli,那么 MySQL_real_escape_string 将无法工作,这就是您将所有内容都设为空白的原因。这将需要一个不存在的基于 MySQL api 的链接资源。使用mysqli_real_escape_string

    //   mysqli_real_escape_string($link,$_POST[$var]);
    
    if(isset($_POST["Comment"]))
    {
        $comment=getPost('Comment',$con);
        echo "The comment is: $_POST[0]";
    }
    function getPost($var,$con)
    {
        return mysqli_real_escape_string($con,$_POST[$var]);
    }
    

    【讨论】:

    • 您需要将$con 作为参数传递给getPost(),或者将其删除global
    • 好的,我已经尝试了这两种更改,但仍然无法正常工作。 MySQL 条目在那里,但注释字段显示为空白,并且没有执行 if 语句。值得一提的是,当我使用 GET 数组时,我在解决之前遇到了类似的问题,但我认为这不是最好的主意。
    • 如果if 语句没有被执行,那么唯一的原因是没有Comment 字段发布到此页面。试试print_r($_POST);
    猜你喜欢
    • 2018-11-25
    • 2017-12-12
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    相关资源
    最近更新 更多