Updating data into MySql database using PHP Form

2019-08-28 02:49发布

问题:

I hope there is someone who can help me. I'm trying to update data into a MySql database using a PHP form with a textarea. As long as I update the database with a random string, which is defined at the beginning of the page, it works fine. But when I try to update the database with the $_POST['text'] I receive from the form, the value in the database is not updated.

I really have no idea what the problem is, so I hope there is someone who can help me to make this work. Please let me know if my question isn't clear enough.

test.php

<html>
<head>
  <script type="text/javascript" src="./js/tinymce/tinymce.min.js"></script>
  <script type="text/javascript">
    tinymce.init({
      selector: "textarea",
      plugins : 'advlist autolink autoresize autosave link image lists charmap media paste preview spellchecker',
      image_advtab: true
    });
  </script>
</head> 

<body>
  <?php
    $con=mysqli_connect("example.com","test","abc123","my_db");
    // Check connection
    if (mysqli_connect_errno())
    {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }                                  

    $result = mysqli_query($con,"SELECT content FROM page_content WHERE page = 'Zangpedagoog'");

    while($row = mysqli_fetch_array($result))
    {
      $text=$row['content'] ;
    }    
  ?>

  <form method="post" action="./send.php">
    <textarea name="text" width="100%">
    <?php echo $text ?>
    </textarea>
    <input id="submit" name="submit" type="submit" value="Send"></form></body></html>

send.php

<?php
  $update = $_POST['text'];
  echo $update;

  $random = '123456';
  echo $random;

  $con=mysql_connect("example.com","test","abc123","my_db");
  // Check connection
  if (!$con)
  {
    echo "Failed to connect to MySQL: " . mysql_connect_error();
  }

  mysql_query("UPDATE page_content SET content=$update WHERE page='Zangpedagoog'",$con);

  mysql_close($con);

?> 

回答1:

I guess it's here:

mysql_query("UPDATE page_content SET content=$update WHERE page='Zangpedagoog'",$con);

You are putting $update directly in the string. That is very dangerous and stupid, but that's not what you came for. The thing that is really causing an error, I guess, is the lack of ''s around $update. Now the value get's directly put into the query, instead of as a string, what I think you want. Keep in mind that this is very open for SQL injections! Fixed code:

mysql_query("UPDATE page_content SET content='$update' WHERE page='Zangpedagoog'",$con);