将数据存储到 MySQL 时出错,但 echo 给出了正确的输出


error in storing data to mysql however echo gives correct output

在我的表格X中,有一些数据看起来像这样

<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')");

}    ?>

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

你有理由使用 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所说,你应该使用预准备语句,你现在拥有的代码容易受到SQL注入的影响。

你的代码有些更正了:

<?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();
?>