如何在MYSQL语句中使用HTML

如何在MYSQL语句中使用HTML

问题描述:

I am trying to write a statement that will update a field in my database which another webpage will read from. Basically it needs to - depending on a user input - update the entry in the database with a preset sentence. This is what I have so far.

Status:
    <form action="" method="post" name="submit">
    <select name="serverstatus">
         <option value="1">Up</option>
         <option value="2">Down</option>
    </select>
    <br>
    <div class="formRow">
        <input type="submit" value="Update" class="mws-button blue" name="serverupdate">
        <div class="clear"></div>
    </div>
    </form>
    <br>
    $serverstatus=$_POST['serverstatus'];
    if(isset($_POST['serverupdate']))
    {
        if ($serverstatus == 1)
        {
        $connect = mysql_connect('sometext', 'sometext', 'sometext', 'sometext');
        if (!$connect) 
        {
            die('Could not connect: ' . mysql_error());
        }
        if (!mysql_select_db('sometext')) 
        {
            die('Could not select database: ' . mysql_error());
        }
        $result = mysql_query('UPDATE `table` SET `field` = "<p style="color:green; display:inline;">sometext.</p>"');
        if (!$result) 
        {
            die('Could not query:' . mysql_error());
        }
        mysql_close($connect);
}

You just need to properly escape your PHP string and query like this:

$result = mysql_query('UPDATE `table` SET `field` = \'<p style="color:green; display:inline;">sometext.</p>\'');

  1. Don't use double quotes in SQL queries, they don't work.
  2. Don't store display logic/styling in your database, you'll have one helluva time trying to change the color from green to notgreen in the future. Hell, that should be in a stylesheet, not inline.
  3. Don't use mysql_* functions, they're deprecated. Learn PDO or MySQLi, you're doing yourself a disservice by not doing so.
  4. Your data needs to be properly escaped and/or paramterized.