-3

Here's what I am trying to do... When a user clicks the submit button in the form (I am using the jQuery Form plugin which is working fine), this should save the content of the textarea in the database. The JavaScript alert should show the last updated ID in the database. But for some reason, although the data is being saved, the JavaScript isn't working, not sure why.

HTML form (index.html):

<form action="submit.php" method="post" id="myForm">
<input type="submit" name="submit" value="Submit"/>
<div id="edit-box">
<textarea id="editor" name="editor"><?php echo $content; ?></textarea>
</div>
</form>

Submit form (submit.php):

<?

// connect to the database
include('connect-db.php');


// get form data, making sure it is valid
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = getRealIPAddress(); //$_SERVER['REMOTE_ADDR'];

// check to make sure both fields are entered
if ($content != '') {

// save the data to the database
mysql_query("INSERT source SET submit_date='$submit_date', ip='$ip_address', content='$content'");
or die(mysql_error());

$lastrow = mysql_query("SELECT MAX(id) FROM source");

echo '<script type="text/javascript"> alert("' . echo $lastrow . '");</script>';

}
?>

Also, do I have to close the connection everytime?

Mumbo Jumbo
  • 360
  • 1
  • 2
  • 12
  • You should always close connections. Always. Also, you're using `echo` when you're concatenating; take it out, that's not how echo works. – Qix - MONICA WAS MISTREATED Mar 08 '13 at 17:06
  • You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). – Quentin Mar 08 '13 at 17:07
  • "the JavaScript isn't working" — We can't see the JavaScript. Look at what the PHP outputs. Is it generating the JavaScript you want? If not, that is what you should ask about. Is so, then show us the JavaScript not the PHP. – Quentin Mar 08 '13 at 17:09
  • `mysql_real_escape_string(htmlspecialchars` — Run `htmlspecialchars` over data before you output it to HTML, not before you insert it into a database. – Quentin Mar 08 '13 at 17:09
  • @Qix Any reference as to why one should always close connections? AFAIK even the deprecated mysql_* extension will automatically close the connection once the script finishes execution. – Fabrício Matté Mar 08 '13 at 17:10
  • @FabrícioMatté It does, but it's always good practice to explicitly close connections. Not just in PHP, but in any language. At least, as long as you're not using a persistent connection, but then the connection's lifetime is **defined** then. – Qix - MONICA WAS MISTREATED Mar 08 '13 at 17:11
  • @Qix As I thought, thanks for confirmation. – Fabrício Matté Mar 08 '13 at 17:13

1 Answers1

0

Why aren't you using 'mysql_insert_id' to get the last inserted id?

$lastrow = mysql_insert_id();
net892z
  • 61
  • 4