Page 1 of 1

Inserting HTML into Mysql Database

Posted: Sun May 09, 2010 4:10 pm
by BKiddo
Hi everyone,

Could really do with some help on this as I'm quite confused.

I want to insert HTML from a within textarea tags in a form into a mysql database. I've tried mysql_escape_string() and addslashes() but I'm still getting an error.

The variables $content, $questions and $marking_guide contain the HTML and text as well.

Here's the code:

Code: Select all

        $content = addslashes($content);
        $questions = addslashes($questions);
        $marking_guide = addslashes($marking_guide);
        $title = addslashes($title);
        
        
        $update = "UPDATE `tablename` SET
        title='$title'
        content='$content',
        questions='$questions',
        questions_num='$questions_num',
        marking_guide='$marking_guide'
        WHERE lesson='$lesson' AND year='$year' AND number='$number'";
            
        $res = mysql_query($update) or die(mysql_error());   
Could someone please help? Thanks in advance!

Re: Inserting HTML into Mysql Database

Posted: Sun May 09, 2010 4:31 pm
by me!
I use two functions (taken from PN)
Give it a shot they work nice ;)

PrepForStore() and PrepForDisplay()



Code: Select all

function PrepForDisplay()
{
    // This search and replace finds the text 'x@y' and replaces
    // it with HTML entities, this provides protection against
    // email harvesters
    static $search = array('/(.)@(.)/se');

    static $replace = array('"&#" .
                            sprintf("%03d", ord("\\1")) .
                            ";@&#" .
                            sprintf("%03d", ord("\\2")) . ";";');

    $resarray = array();
    foreach (func_get_args() as $ourvar) {
        // Prepare var
        $ourvar = htmlspecialchars($ourvar);
        $ourvar = preg_replace($search, $replace, $ourvar);
        // Add to array
        array_push($resarray, $ourvar);
    }
    // Return vars
    if (func_num_args() == 1) {
        return $resarray[0];
    } else {
        return $resarray;
    }
}



/**
* ready database output
* Gets a variable, cleaning it up such that the text is
* stored in a database exactly as expected
*
* @param var $ variable to prepare
* @param  $ ...
* @return mixed prepared variable if only one variable passed
* in, otherwise an array of prepared variables
*/
function PrepForStore()
{
    $resarray = array();
    foreach (func_get_args() as $ourvar) {
        if (!get_magic_quotes_runtime() && !is_array($ourvar)) {
            $ourvar = addslashes($ourvar);
        }
        // Add to array
        array_push($resarray, $ourvar);
    }
    // Return vars
    if (func_num_args() == 1) {
        return $resarray[0];
    } else {
        return $resarray;
    }
}

Re: Inserting HTML into Mysql Database

Posted: Sun May 09, 2010 4:57 pm
by BKiddo
I haven't got time to do this tonight, but really grateful for the help me! Thanks so much!!! :mrgreen: