Page 1 of 1

problem with INSERT queries, nothing has been stored

Posted: Thu Nov 08, 2007 9:40 am
by Bon Bon
I am having a problem with INSERT queries with the following snippet. I am running INSERT queries and no errors are being reported although when I check in the database, nothing has been stored.

As a temporary measure I am using the procedural style to store the data in the database as this works. The SQL executed has no errors as I have checked that. I hope this provides you with enough information to get an idea of what is happening.

Thanks in advance.

Code: Select all

<?php

class Database {
  static private $_mysqli;

  final private function _dbConnect () {
    return self::$_mysqli->real_connect('127.0.0.1', 'root', '********', '********_co_uk_-_main');
  }

  private function __construct () {
    self::$_mysqli = mysqli_init();
    self::$_mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT=0');
    self::$_mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
    self::_dbConnect();
    if (mysqli_connect_errno()) trigger_error('The database connection failed', E_USER_ERROR);
  }

  final public function escape ($variable) {
    $string = (string) $variable;
    if (get_magic_quotes_gpc()) $string = stripslashes($string);
    return self::$_mysqli->real_escape_string($string);
  }

  protected function _query ($sql) {
    if (self::$_mysqli->real_query($sql)) return self::$_mysqli->store_result();
    else trigger_error("Query failed: $sql", E_USER_WARNING);
    return FALSE;
  }
}

class Table extends Database {
  protected $_table = ''; // set in parent class

  public function insert ($data) {
    foreach ($data as $field => $value) {
      $fields[] = "`" . $this->escape($field) . "`";
      $values[] = "'" . $this->escape($value) . "'";
    }

    $fields = implode(', ', $fields);
    $values = implode(', ', $values);

    $sql = 'INSERT INTO `' . $this->escape($this->_table) . "` ($fields) VALUES($values);";

    parent::_query($sql);
  }
}

?>

Posted: Thu Nov 08, 2007 2:34 pm
by jonwondering
just a quick glance at your code - how come you dont tell it WHERE to insert?

Posted: Thu Nov 08, 2007 4:57 pm
by Bon Bon
Sorry, to insert I am using the following code:

Code: Select all

$sql['field_name'] = $value;
$db->table->insert($sql);
That is the format I use.

Another thing I think might be worth mentioning is the fact that the table rows are actually auto-incramented when the SQL is inserted although no data is ever inserted. Might this have something to do with where I run the real_escape_string method in the class?

Cheers.