User Tools

Site Tools


runsql

Execute an SQL statement on a MySQL DB

 
function runSQL($sql_string) {
 
  global $config;    
  $link =	mysql_connect ($config['db_server'], $config['db_user'], $config['db_password']) or die("DB Connection Error");
  $result = mysql_db_query($config['db_database'],$sql_string,$link) or die("Database Problem :".mysql_error($link)."\n<br />\n".$sql_string);
  //mysql_db_query returns 1 on a insert statement -> no need to ask for results
 
  if ($result != 1) {
    for($i=0; $i< mysql_num_rows($result); $i++) {
      $temparray = mysql_fetch_assoc($result);
      $resultarray[]=$temparray;
    }
    mysql_free_result ($result);
  }
 
  if (mysql_insert_id($link)) {
    $resultarray = mysql_insert_id($link); //give back ID on insert
  }
 
  mysql_close ($link);
  return $resultarray;
} 
Note a few things about this code
  • The global $config must be set somewhere.
  • The $sql_string variable does not have a default value, –it probably should if unsafe users have access(as I rush off to change my own code!)
  • mysql has an “improved” extension, but it's not as simple as changing all mysql_ to mysqli_
  • this is a generic function, –you might want to use full database.table syntax if using this query out of the box
  • There is another way to write queries to take advantage of OOP (start here)
runsql.txt · Last modified: 2006/11/09 16:36 by 216.254.60.114