将数据存储到mysql时出错,但echo提供正确的输出

时间:2012-08-15 19:04:28

标签: php mysql

在我的tableX中,有些数据看起来像这样

<h1>ghhhhhh!</h1>
http://twitter.com/USERNAME
<h1></h1>
       http://3.bp.blogspot.com/_fqPQy3jcOwE/TJhikN8s5lI/AAAAAAAABL0/3Pbb3EAeo0k/s1600/Srishti+Rai1.html
<h1></h1>
http://4.bp.blogspot.com/_fqPQy3jcOwE/TJhiXGx1RII/AAAAAAAABLc/XNp_y51apks/s1600/anus7.html
<h1></h1>
http://cyz.com/_fqPQy3jcOwE/TJhh1ILX47I/AAAAAAAABKk/gX-OKEXtLFs/s1600/4r-2.html
<h1></h1>
http://cyz.com/_fqPQy3jcOwE/TJhiHGgb-KI/AAAAAAAABK8/zEv_41YzMhY/s1600/19+(1).html
<h1></h1>
http://cyz.com/_fqPQy3jcOwE/TJhihkpZZKI/AAAAAAAABLs/zDnlZkerBd8/s1600/Pooja+Gurung.html

当我回显相同的PHP代码时,它提供了正确的输出但是当我在mysql中存储这些细节时,只有一行存储在mysql行中。 我的代码就是这个

<?php 

include('connect.php'); 



 $idmg=$_POST["id"];
 $res =mysql_query("select * from tablea");
 $row = mysql_fetch_array($res);

if(sus== '0'){ 

  $output=''.$row['content'].''; 


 echo $output;//this output gives the above result but when i store in db it stores first row


mysql_query ("INSERT INTO tablea (content) VALUES ('$output')");


}    ?>

3 个答案:

答案 0 :(得分:2)

你有sql_fetch_array()而不是mysql_fetch_array()的原因吗?

如果您想要多行,还需要遍历结果。

<?php  
include('connect.php');   
$idmg =$_POST["id"]; 
$res  =mysql_query("select * from tablea"); 
$row  = sql_fetch_array($res)
  if($sus== '0'){  
   $output=mysql_real_escape_string($row['content']); 
   echo $output;
   mysql_query ("INSERT INTO tablea (content) VALUES ('$output')");  
}
?> 

正如@DCoder所说,你应该使用prepared statements,你现在的代码很容易被SQL注入。

答案 1 :(得分:2)

您的插入失败,因为您在$output中有未转义的数据。按照DCoder的建议,使用PDO或mysqli。

答案 2 :(得分:1)

你的代码有些 - 更正了:

<?php
    include('connect.php'); 

    $idmg=$_POST["id"];
    $res = mysql_query("select * from tablea");
    $row = mysql_fetch_array($res);

    if($sus== '0'){  // what is sus? If variable.. should be $sus
        $output = $row['content']; // .'' is literally nothing.. 
        echo $output;

        mysql_query ("INSERT INTO tablea (content) VALUES ('$output')");
    }
?>

我认为你想要做的事情:

<?php
    include('connect.php'); 

    $idmg = $_POST["id"]; // not actually used
    $res = mysql_query('SELECT * FROM tablea');
    while($row = mysql_fetch_array($res)) {
        $output = $row['content'];
        echo $output;
        // do anything else you want.. in your case ?enter the data back in?
        mysql_query("INSERT INTO tablea(content) VALUES('$output')");
    }
?>

你应该使用什么:

<?php
    $idmg = $_POST['id']; // <-- not actually used
    $res = $mysqli_connection->query('SELECT * FROM tablea');
    while($row = $res->fetch_array(MYSQLI_ASSOC)) {
        $output = mysqli_connection->real_escape_string($row['content']);
        echo $output;
        // Do whatever else you like
        $mysqli_connection->query("INSERT INTO tablea(content) VALUES('$output')");
    }
    $res->free();
    $mysqli_connection->close();
?>