0

I am trying INSERT JavaScript/CSS/code into a MYSQL database. Adcode is being passed from a textarea to the PHP code below, Upon INSERT is successful with the adname, but blank with adcode..

QUESTIONs/ISSUE:

  1. Why is it inputting blank code into the database instead of the code being passed
  2. What is the most efficient why of doing this?
  3. How can I pass the Adname and Adcode and UPDATE at the same time.

My FIRST code:Version 1 (fixed issue/question 1 in version two of the code below)

// Insert ad into database
    $ad = mysql_real_escape_string($_POST['adcode']);
    $insert = "INSERT INTO ads (adname, adcode) VALUES ('".$_POST['adname']."', '".$_POST['$ad']."')";
    $doit = mysql_query($insert);

My current code :Version 2 (for questions one and two)

if ($_GET['action'] == "editad") {  // Edit AD
    $newadcode = mysql_real_escape_string($_POST['adcode' . $ID]);
    $doedit = "UPDATE `adgate`.`ads` SET `ads`.`adcode` = '$newadcode' WHERE `ads`.`ID` = '$ID' LIMIT 1" or die(mysql_error());
    $retval = mysql_query( $doedit, $connection );
    if(! $retval )
    {
        die('Could not update data: ' . mysql_error());
    }
    echo "Updated data successfully\n";
    //header("Location: displayads.php");
3
  • 3
    Careful; that’s rather vulnerable to SQL injection. You should escape $_POST['adname'] and $_POST['$ad'], too, before putting them into the query. Even better, you could use prepared statements and PDO-MySQL or MySQLi 😊
    – user1675187
    Oct 5, 2012 at 2:52
  • how can i escape out of it. sorry I am just learning php. thanks for all the help!
    – Caiapfas
    Oct 5, 2012 at 3:18

2 Answers 2

1

Try:

$adname = mysql_real_escape_string($_POST['adname']);
$adcode = mysql_real_escape_string($_POST['adcode']);
$insert = "INSERT INTO ads (adname, adcode) VALUES ('".$adname."', '".$adcode."')";
$doit = mysql_query($insert);
1
  • @Caiapfas No worries, welcome to Stackoverflow, and good luck with PHP!
    – Stegrex
    Oct 5, 2012 at 3:37
1

Spot the mistake:

$ad = mysql_real_escape_string($_POST['adcode']);
^^^
... "... VALUES ('".$_POST['adname']."', '".$_POST['$ad']."')";
                                            ^^^^^^^^^^^^^

Enable error reporting during development! This would have thrown a nice warning.

1
  • thanks good info. turned it on and found the issue and then some...LOL
    – Caiapfas
    Oct 5, 2012 at 3:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.