sábado, 5 de mayo de 2012

Check if record exists in MySQL table with php

So Hello again,

this time I come with a little nice code snippet, that will help you to easily check if a record exists in a MySQL table, so for example I will take the task "check if a username exists in the users table"

for this you will need two functions:


function connect(){ 
  include('config.php'); //where you have your db stuff saved
  $link = mysql_connect($db_host, $db_user, $db_pass);
  if(!$link){
   die('ERROR: 001');
  }
  return $link;
 }


this can be replaced by your favourite way to connect to the database, so next function:



function check($table, $fields, $values) { 
  if((count($fields) > count($values)) || count($values) > count($fields)) die('ERROR 004');
  include('config.php');
  $link = connect();
  mysql_select_db($db_name);
  $check_query = 'SELECT ';
  for($i=0;$i<count($fields);$i++){
   $check_query .= $fields[$i].',';
  }

  $check_query = rtrim($check_query, ',');
  $check_query .= ' FROM '.$table.' WHERE ';

  for($i=0;$i<count($fields);$i++){
   $check_query .= $fields[$i].'=' .$values[$i] . ' AND ';
  }

  $check_query = substr($check_query, 0, -4).';';
  $result = mysql_query($check_query);
  if(!$result){
   die('ERROR: 005 ');
  }

  $count = mysql_num_rows($result);
  if($count > 0) die('username taken!');
}

here there are 3 parameters:

  • Table: the table name you want to query
  • Fields: the fields you want to query
  • Value: the values you want to query
notice that fields and values must have the same count() otherwise it wont work!

so the usage should be:


check('users', array('username'), array('\''.$username.'\''));

if you want to compare more values, just make the arrays bigger and dont forget the " ' " in varchar or texts.

this is an easy way to kill the pain of writting querys over and over again. I hope it helps you out.

Happy codding.


No hay comentarios:

Publicar un comentario