Kelly Kelly - 4 years ago 112
SQL Question

Get value from text box and see if value exist in mysql

I am trying to get the value from a text box. I know I can do this with Javascript.

What I don't know how to do is take that value then run it through PHP to see if the value is in mysql db. I can do this after the forum is submitted but what I would like to have happen is have the text box turn yellow if the value is not listed in mysql.

Do I need to get the value of the text area and then request a PHP page?

How would I got about this?

I am assuming I do this with jQuery?

Answer Source

I havent run this, but it should be something along these lines:

In your html:

<script>
$.ajax({
  url : 'something.php',
  dataType : 'json',
  type : 'POST',
  data : {
    something : $('#something').val()
  }
}).then(function(data) {
  if(data.result == 'ok') {
    // do something with data.count ...
  } else {
    if(data.message) {
      alert(data.message);
    }
  }
});
</script>

then in something.php:

<?php

if(array_key_exists('something', $_POST)) {
  $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
  $stmt = $db->prepare("SELECT * FROM table WHERE something = ?");
  $stmt->execute(array($_POST['something']));
  echo json_encode(array('result'=>'ok','count'=>$stmt->rowCount()));
} else {
  echo json_encode(array('result'=>'error','message'=>'no input'));
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download