User Tools

Site Tools


runsql

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
runsql [2005/10/05 07:55] 209.8.22.201runsql [2006/11/09 16:36] (current) 216.254.60.114
Line 1: Line 1:
 +====== Execute an SQL statement on a MySQL DB ======
 +
 +<code php>
 +
 +
 +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;
 +
 +</code>
 +
 +
 +== 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 ([[http://www.php.net/manual/en/ref.mysqli.php|start here]])
 +