虽然循环拒绝工作

时间:2012-12-10 03:42:21

标签: php mysql for-loop mysqli while-loop

我以前做了一个帖子,但是无法正确解释我的问题,也无法解决问题。这就是我所拥有的。

$shoutlines = file($shout_file);

$aTemp = array();
foreach($matches['user'] as $user) {
    $aTemp[] = "'" . $user . "'";
}
$user = implode(",", $aTemp);

$rara = "SELECT * FROM accounts WHERE username IN ( $user )"; // Tried this statment both as a query and prepared statement
$getlevel = $db->query("SELECT * FROM accounts WHERE username IN '( ".$user." )'"); // Tried this both as a query and prepared statement
//$getlevel->bind_param('s', $user);
//$getlevel->execute();
//$level = $getlevel->get_result();
//$getlevel->store_result();
while($getdb = $getlevel->fetch_assoc()){
    //output the html
        for($i = 0; $i < (1000); $i++)
        {
            if(isset($shoutlines[$i]))
            {

                $shoutline = preg_replace('/<\/div>\n/', ' ', $shoutlines[$i], 1);
                echo showSmileys($shoutline) . "<div class='delete'><a href='javascript: delete_shoutline({$i});' title='Delele'>delete</a></div></div>";
            }
        }
}

我在for循环中有while循环不会在其中运行,如果我将for循环移到while之外它可以正常运行,但是我需要在while循环中检查用户是否保存在我的数据库中的帖子标题,能力等。我已经展示了到目前为止我已经尝试过什么来识别问题,如果查询,绑定或执行没有显示真实,我已经尝试消除错误,但现在点击了。这个代码被拉出来,因此你的阅读能力没有太多杂乱,对此的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

当“爆炸”用户名时,你需要用引号括起每个用户名,而不是整个用户名。同时使名称对数据输入安全。

$aTemp = array();
foreach($matches['user'] as $user) {
    $aTemp[] = '"' . mysql_real_escape_string($user) . '"';
}
$user = implode(",", $aTemp);

然后使用第一个查询:

"SELECT * FROM accounts WHERE username IN ( $user )";

编辑:添加错误检查:

$getlevel = $db->query("SELECT * FROM accounts WHERE username IN ( $user )");
if ($getlevel == false) {
    // Normally you'll build into a function or class, but this is the simple example
    // Never output SQL errors on a live site, but log to file or (if you can do it safely) the database.
    echo 'Whoopsie<br />';
    var_dump($db->errorInfo());
    exit();
}

答案 1 :(得分:0)

使用与IN子句的数据绑定并不是那么好,所以如果你真的需要IN并且不关心使用旧的,已弃用的mysql_*函数,请试试这个:< / p>

$user="'".implode("','",array_map(function($s){
  return mysql_real_escape_string($s);
},$matches["user"])."'";
$rara="SELECT * FROM accounts WHERE username IN ($user)";