title: How to insert into SQL using PHP and AJAX?
body: <p>I have looked at this post: <a href="https://stackoverflow.com/questions/5143191/inserting-into-mysql-from-php-jquery-ajax">Inserting into MySQL from PHP (jQuery/AJAX)</a> but I didn't get the code to work. It's a quite old post so it might not work anymore?</p>
  
  <p>I want to insert a post from my website (PHP) into my database (MySQL) without updating the page. I'm looking at AJAX (for example the link above) but I don't understand how to get it to work.</p>
  
  <p>I have also looked at this video: <a href="https://www.youtube.com/watch?v=lwo4fAqaVFM" rel="nofollow noreferrer">https://www.youtube.com/watch?v=lwo4fAqaVFM</a> for loading data and that's very simple so I thought it would be as simple to insert, but it wasn't...</p>
  
  <p>Can anyone help me?</p>
  
  <p>This new save.php actually works.</p>
  
  <p><strong>index.php</strong></p>
  
  <pre><code>&lt;head&gt;
      &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt;
      &lt;script type="text/javascript" src="jquery.js"&gt;&lt;/script&gt;
  &lt;/head&gt; 
  
  &lt;body&gt;
      &lt;form id="example" method="post"&gt;
          &lt;input name="textbox"&gt;
          &lt;input type="button" name="submitbuttonname" value="submit" onClick="$.post('save.php', $('form#example').serialize())"&gt;
      &lt;/form&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p><strong>New save.php</strong></p>
  
  <pre><code>$db = new mysqli('localhost','root','','audf');
  mysqli_set_charset($db, 'utf8') or die('Charset kunde inte ändras till UTF-8');
  
  if($db-&gt;connect_errno){
      die('Sorry, we are having some problems.');
  }
  $firstName = $_POST["firstName"];
  
  $db-&gt;query("INSERT INTO test_db (first_name) VALUES ('".$firstName."')");
  </code></pre>
  
  <p><strong>Old save.php</strong></p>
  
  <pre><code>$db = new mysqli('localhost','root','','audf');
  mysqli_set_charset($db, 'utf8') or die('Charset kunde inte ändras till UTF-8');
  
  if($db-&gt;connect_errno){
      die('Sorry, we are having some problems.');
  }
  
  if($_POST["submitbuttonname"]) {
      $q = $db-&gt;prepare("INSERT INTO test_db (first_name) VALUES (?)");
      $q-&gt;execute(array($_POST["textbox"]));
  }
  </code></pre>